[英]How to subtract one object array literally from another object Array
I think my question is pretty easy but as I am beginning to learn javascript I'm stuck with the following. 我认为我的问题很简单,但是当我开始学习JavaScript时,请牢记以下内容。 I have 2 object arrays which contain some same Ids which can be multiple duplicates.
我有2个对象数组,其中包含一些相同的ID,可以重复多个。 I want to subtract the same Ids in the arrays from each other with plain javascript no libraries.
我想用简单的javascript no库彼此减去数组中的相同ID。 I found this filter method but it removes all the objects with the criteria.
我找到了此过滤器方法,但它删除了所有符合条件的对象。 I expect only the amount of Ids removed fulfilling the criteria which can be found in the array to be subtracted.
我希望仅除去满足以下条件的Id数量即可在数组中找到该条件。
Here is my example: 这是我的示例:
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/ http://jsfiddle.net/vy6fcgrc/29/
I expect: 我预计:
newFilter = [{"Id":"123","Name":"OPL-00074051","arrayPicklist":"Categorie__c"},{"Id":"123","Name":"OPL-00074045","arrayPicklist":"Regio__c"}]
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.