问题描述
_.intersection([], [])
只适用于原始类型,对吗?
only works with primitive types, right?
它不适用于对象。如何使它与对象一起工作(可能通过检查Id字段)?
It doesn't work with objects. How can I make it work with objects (maybe by checking the "Id" field)?
var a = [ {'id': 1, 'name': 'jake' }, {'id':4, 'name': 'jenny'} ]
var b = [ {'id': 1, 'name': 'jake' }, {'id': 9, 'name': 'nick'} ]
在此例如,结果应为:
_.intersection(a, b);
推荐答案
您可以根据下划线的功能创建另一个功能。您只需要从原始函数更改一行代码:
You can create another function based on underscore's function. You only have to change one line of code from the original function:
_.intersectionObjects = function(array) {
var slice = Array.prototype.slice; // added this line as a utility
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
//return _.indexOf(other, item) >= 0;
return _.any(other, function(element) { return _.isEqual(element, item); });
});
});
};
在这种情况下,您现在使用下划线的isEqual()方法而不是JavaScript的相等比较器。我用你的例子尝试了它并且它有效。以下是关于isEqual函数的下划线文档的摘录:
In this case you'd now be using underscore's isEqual() method instead of JavaScript's equality comparer. I tried it with your example and it worked. Here is an excerpt from underscore's documentation regarding the isEqual function:
_.isEqual(object, other)
Performs an optimized deep comparison between the two objects, to determine if they should be considered equal.
您可以在此处找到文档:
You can find the documentation here: http://documentcloud.github.com/underscore/#isEqual
我忍受了jsFiddle上的代码,以便您可以测试并确认它:
I put up the code on jsFiddle so you can test and confirm it: http://jsfiddle.net/luisperezphd/jrJxT/
这篇关于如何使用下划线的“交叉点”对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!