2016-03-15 188 views
1

我正在處理角js,我對它很陌生。所以我被困在一個問題,我必須減去兩個包含對象的數組。過濾包含基於另一個包含角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實現這一目標的對象來填充「newArray」變量?由於

回答

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>');

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>')

0

與線性複雜度的提案。

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>');

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; 
}); 
相關問題