例如:
const a={颜色:红、绿、蓝,水果:苹果、香蕉}
const b={color:红、黑、蓝}
someFucntion(a,b);//结果{color:红,蓝}
考虑到可能有任意数量的键具有任意长度的数组的值。请帮我找到完美的解决方案。
谢谢。
发布于 2020-06-25 11:05:30
我的一个同事给了我下面的函数,这正是我想要的。
//Making the assumption that all values are arrays.
//Probably a more efficient way of doing this.
const a = { color: ["red", "green", "blue"], fruits: ["apple", "banana"] };
const b = {color: ["red", "black", "blue"] };
console.log(someFucntion(a, b)); // result { color:[red, blue] }
function someFucntion(objOne, objTwo) {
// Find intersecting keys and values and return them.
let finalObj = {};
// Only need to check one. If it isn't in here, it doesn't matter
// if it is in the other.
for (const key in objOne) {
// Check if key is in other object.
if (key in objTwo) {
// Assumes all values are arrays.
finalObj[key] = [];
// Populate with shared values.
objOne[key].forEach(el => {
if (objTwo[key].includes(el)) {
finalObj[key].push(el);
}
});
}
}
return finalObj;
}
https://stackoverflow.com/questions/62548857
复制相似问题