如何找到与两个数组相交的所有对象? [英] How to find all OBJECTS that intersect two arrays?
本文介绍了如何找到与两个数组相交的所有对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有两个对象数组,例如:
If I have two arrays of objects, like this:
var a1 = [{"a":"b"}, {"b":"c"}, {"d":"e"}],
a2 = [{"g":"h"}, {"a":"b"}, {"i":"j"}]
(请注意,对象可以是任何结构,如此简单)
(note that objects may be of any structure, not so simple)
提取两个数组中所有对象的最有效方法是什么?
what is the most efficient way to extract all the objects that are in both arrays?
我检查了以下问题:在多个JavaScript数组之间查找匹配项,但这不是相同...
I checked this question: Finding matches between multiple JavaScript Arrays, but this is not the same...
推荐答案
您可以使用 JSON 展平对象.stringify()
,然后检查交叉点。
You can flatten the objects using JSON.stringify()
and then check for intersection.
var a1 = [{"a":"b"}, {"b":"c"}, {"d":"e"}],
a2 = [{"g":"h"}, {"a":"b"}, {"i":"j"}]
// flatten objects in second array
var stringifiedA2 = a2.map(function(x) {
return JSON.stringify(x);
});
// get intersecting objects
var intersecting = a1.filter(function(x) {
return stringifiedA2.indexOf(JSON.stringify(x)) !== -1;
});
相交
将包含对象 { a: b}
这篇关于如何找到与两个数组相交的所有对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文