目前我正在关注一本书并且非常困惑,并且多次尝试了解以下代码.我的第一个困惑实际上是接近比较两个对象a和b的问题.
function deepEqual(a, b) {
if (a === b) return true;
if (a == null || typeof a != "object" ||
b == null || typeof b != "object")
return false;
var propsInA = 0, propsInB = 0;
for (var prop in a)
propsInA += 1;
for (var prop in b) {
propsInB += 1;
if (!(prop in a) || !deepEqual(a[prop], b[prop]))
return false;
}
return propsInA == propsInB;
}
var obj = {here: {is: "an"}, …Run Code Online (Sandbox Code Playgroud) 我无法弄清楚如何找到这组数组的交集:
[
[
{"name":"product1","light":"1"},
{"name":"product2","light":"2"},
{"name":"product5","light":"5"},
{"name":"product4","light":"4"}
],
[
{"name":"product2","light":"2"},
{"name":"product3","light":"3"},
{"name":"product4","light":"4"}
],[...more arrays with objects]
]
Run Code Online (Sandbox Code Playgroud)
这只是样本数据,真实的集合我已经改变很多,但具有这种结构.我希望返回的交集看起来像这样(交叉对象的单个数组):
[
{"name":"product2","light":"2"},
{"name":"product4","light":"4"},
]
Run Code Online (Sandbox Code Playgroud)
我和LoDashjs以及Underscorejs一起尝试了这个:
_.intersectionObjects = _.intersect = 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); });
});
});
};
Run Code Online (Sandbox Code Playgroud)
我需要这个,因为我正在尝试使用knockoutjs创建一个标签系统.我有一个分类标签按钮的布局,在点击时写入"过滤器"可观察数组,唯一剩下的就是找到此可观察数组中包含的过滤产品的交集.
请帮帮我,我一直试图连续两天解决这个问题,但缺乏javascript知识来解决这个问题.提前致谢!
javascript multidimensional-array underscore.js knockout.js lodash