【发布时间】:2020-06-24 06:18:39
【问题描述】:
例如:
const a={color:[red,green,blue],fruits:[apple,banana]}
const b ={color:[红、黑、蓝]}
一些函数(a,b); //结果{颜色:[红色,蓝色]}
考虑到可能有任意数量的键,其值是任意长度的数组。请帮我找到完美的解决方案。
谢谢。
【问题讨论】:
标签: object intersection
例如:
const a={color:[red,green,blue],fruits:[apple,banana]}
const b ={color:[红、黑、蓝]}
一些函数(a,b); //结果{颜色:[红色,蓝色]}
考虑到可能有任意数量的键,其值是任意长度的数组。请帮我找到完美的解决方案。
谢谢。
【问题讨论】:
标签: object intersection
我的一位同事给了我以下功能,这正是我想要的。
//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;
}
【讨论】: