我认为我的问题非常简单,但随着我开始学习javascript,我坚持使用以下内容。 我有2个对象数组,包含一些相同的ID,可以是多个重复。我想用普通的javascript没有库来减去数组中相同的ID。我找到了这个过滤方法,但它删除了所有符合条件的对象。 我预计只有删除的ID数量符合可以在数组中找到的标准。
以下是我的例子:
var filter = [{"Id":"123","Name":"OPL-00074045","arrayPicklist":"Categorie__c"},{"Id":"124","Name":"OPL-00074051","arrayPicklist":"Categorie__c"}]
var filter2 = [{"Id":"123","Name":"OPL-00074045","arrayPicklist":"Categorie__c"},{"Id":"123","Name":"OPL-00074051","arrayPicklist":"Categorie__c"},{"Id":"123","Name":"OPL-00074045","arrayPicklist":"Regio__c"}]
var newFilter = filter2.filter(o => !filter.find(o2 => o.Id === o2.Id && o.arrayPicklist === o2.arrayPicklist));
console.log(JSON.stringify(newFilter));
http://jsfiddle.net/vy6fcgrc/29/
我期待:
newFilter = [{"Id":"123","Name":"OPL-00074051","arrayPicklist":"Categorie__c"},{"Id":"123","Name":"OPL-00074045","arrayPicklist":"Regio__c"}]
答案 0 :(得分:0)
var filter1 = [{"Id":"123","Name":"OPL-00074045","arrayPicklist":"Categorie__c"},
{"Id":"124","Name":"OPL-00074051","arrayPicklist":"Categorie__c"}]
var filter2 = [{"Id":"123","Name":"OPL-00074045","arrayPicklist":"Categorie__c"},
{"Id":"123","Name":"OPL-00074051","arrayPicklist":"Categorie__c"},
{"Id":"123","Name":"OPL-00074045","arrayPicklist":"Regio__c"}]
var props = ["Id","Name", "arrayPicklist"];
var result = filter1.filter(function(o1){
// filter out (!) items in result2
return !filter2.some(function(o2){
return (o1.Id === o2.Id && o1.arrayPicklist===o2.arrayPicklist) ; // assumes unique id
});
}).map(function(o){
// use reduce to make objects with only the required properties
// map to apply this to the filtered array as a whole
return props.reduce(function(newo, arrayPicklist){
newo[arrayPicklist] = o[arrayPicklist];
return newo;
}, {});
});
alert(JSON.stringify(result));