[英]Intersection and Equals between arrays of objects by only some fields with underscore.js
I'm using underscore.js on my project and i want to compare two arrays but only their intersection by one field. 我在我的项目上使用underscore.js,我想比较两个数组,但仅按一个字段比较它们的交集。
The first array : 第一个数组:
[{item: myObject1, label: myObject1.name, ticked: true, disabled: false}]
the second array : 第二个数组:
[{item: myObject1, label: myObject1.name, ticked: false, disabled: false},
{item: myObject2, label: myObject2.name, ticked: true, disabled: false}]
I want to return intersection of these arrays by myObject.id and compare it : 我想通过myObject.id返回这些数组的交集并进行比较:
intersection : 交叉点:
{item: myObject1, label: myObject1.name, ticked: true, disabled: false}
and 和
{item: myObject1, label: myObject1.name, ticked: false, disabled: false}
because myObject1 is the intersection (myObject1.id == myObject1.id). 因为myObject1是交集(myObject1.id == myObject1.id)。
I don't see how can i do that with underscore.js. 我看不到如何使用underscore.js。
EDIT: 编辑:
with only isEqual function, i can do that (i use AngularJS): 仅使用isEqual函数,我可以做到这一点(我使用AngularJS):
isIOEquals: function(inputs, outputs){
var editedInputs = [];
var editedOutputs = [];
angular.forEach(outputs, function(outputItem){
angular.forEach(inputs, function(inputItem){
if(_.isEqual(inputItem.item.id, outputItem.item.id)){
editedInputs.push(inputItem);
editedOutputs.push(outputItem);
}
});
});
return _.isEqual(editedInputs, editedOutputs);
}
I believe this will do the job. 我相信这会做的。
function myIntersection() {
var objectLists = [].slice.call(arguments),
objMapper = objectLists.pop();
var flatLists = objectLists.map(function(lst) {
return lst.map(objMapper);
});
// There will be duplicates in this list, but maybe that's the desired
// behaviour, so I'll leave it to you to sort that out.
var mergedObjectLists = _.flatten(objectLists);
var intersectingValues = _.intersection.apply(null, flatLists);
return mergedObjectLists.filter(function(obj) {
return intersectingValues.indexOf(objMapper(obj)) !== -1
});
}
myIntersection(list1, list2, function(obj) {return obj.item.id});
I'd love to see other approaches. 我希望看到其他方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.