根据包含角度js中对象的另一个数组过滤包含对象的数组

时间:2016-03-15 10:21:01

标签: javascript arrays angularjs

我正在研究角度js,我是新手。所以我遇到了一个问题,我必须减去两个包含对象的数组。

For Eg.

var all = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}];
var old = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];

var newArray = [];

现在,我想填充新的阵容'变量与旧的'中不存在的对象列表如下

newArray = [{id:'2',name:'B'},{id:'4',name:'D'}]

无论如何在角度js中实现这一点?感谢

4 个答案:

答案 0 :(得分:1)

试试这个

var all = [{
  id: '1',
  name: 'A'
}, {
  id: '2',
  name: 'B'
}, {
  id: '3',
  name: 'C'
}, {
  id: '4',
  name: 'D'
}];
var old = [{
  id: '1',
  name: 'A',
  state: 'healthy'
}, {
  id: '3',
  name: 'C',
  state: 'healthy'
}];

var newlist = all.filter(function(a) {
  return old.filter(function(o) {
    return o.id == a.id
  }).length == 0
})
document.write('<pre>' + JSON.stringify(newlist, 0, 4) + '</pre>')

答案 1 :(得分:0)

线性复杂的提案。

&#13;
&#13;
var all = [{ id: '1', name: 'A' }, { id: '2', name: 'B' }, { id: '3', name: 'C' }, { id: '4', name: 'D' }],
    old = [{ id: '1', name: 'A', state: 'healthy' }, { id: '3', name: 'C', state: 'healthy' }],
    result = function (array1, array2) {
        var o = {};
        array2.forEach(function (a) {
            o[a.id] = true;
        });
        return array1.filter(function (a) {
            return !o[a.id];
        });
    }(all, old);

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');
&#13;
&#13;
&#13;

答案 2 :(得分:0)

这与AngularJS完全无关。这是一个javascript问题,您可以使用以下代码轻松实现此结果 -

var new = all.filter(function(element) { 
    var res = $.grep(old, function(el) { 
        return el.id == element.id; 
    }); 
    if(res.length == 0) return element; 
});

答案 3 :(得分:0)

您可以使用Array.prototype.forEach()Array.prototype.some()

执行此操作

var all = [{id:'1',name:'A'},{id:'2',name:'B'},{id:'3',name:'C'},{id:'4',name:'D'}];
var old = [{id:'1',name:'A',state:'healthy'},{id:'3',name:'C',state:'healthy'}];

var newArr = [];

all.forEach(function(e) {
    if(!old.some(s => s.id == e.id)) {
        newArr.push(e);
    }
});

document.write('<pre>' + JSON.stringify(newArr, 0, 2) + '</pre>');