获得两个对象的交叉点的最佳方法是什么? [英] Best way to get intersection of keys of two objects?
问题描述
我有两个像这样的对象文字:
I have two object literals like so:
var firstObject =
{
x: 0,
y: 1,
z: 2,
a: 10,
b: 20,
e: 30
}
var secondObject =
{
x: 0,
y: 1,
z: 2,
a: 10,
c: 20,
d: 30
}
我想得到这两个对象的交叉点文字是这样的:
I want to get the intersection of the keys these two object literals have like so:
var intersectionKeys = ['x', 'y', 'z', 'a']
我显然可以做一个循环,看看另一个对象中是否存在同名的密钥,但是我想知道这对于某些函数式编程和map / filter / reduce用法是否是一个好例子?我自己还没有做那么多函数式编程,但我有一种感觉,可能存在一个干净而聪明的解决方案来解决这个问题。
I can obviously do a loop and see if a key with the same name exists in the other object, but I am wondering if this would be a good case for some functional programming and map / filter / reduce usage? I myself have not done that much functional programming, but I have a feeling, that there could exist a clean and clever solution for this problem.
推荐答案
没有 indexOf
的解决方案。
var firstObject = { x: 0, y: 1, z: 2, a: 10, b: 20, e: 30 },
secondObject = { x: 0, y: 1, z: 2, a: 10, c: 20, d: 30 };
function intersection(o1, o2) {
return Object.keys(o1).concat(Object.keys(o2)).sort().reduce(function (r, a, i, aa) {
if (i && aa[i - 1] === a) {
r.push(a);
}
return r;
}, []);
}
document.write('<pre>' + JSON.stringify(intersection(firstObject, secondObject), 0, 4) + '</pre>');
O(n)的第二次尝试。
Second attempt with O(n).
var firstObject = { x: 0, y: 1, z: 2, a: 10, b: 20, e: 30 },
secondObject = { x: 0, y: 1, z: 2, a: 10, c: 20, d: 30 };
function intersection(o1, o2) {
return Object.keys(o1).filter({}.hasOwnProperty.bind(o2));
}
document.write('<pre>' + JSON.stringify(intersection(firstObject, secondObject), 0, 4) + '</pre>');
这篇关于获得两个对象的交叉点的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!