首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在JS中提取两个对象的交叉键及其交叉值?

如何在JS中提取两个对象的交叉键及其交叉值?
EN

Stack Overflow用户
提问于 2020-06-24 14:18:39
回答 1查看 21关注 0票数 0

例如:

const a={颜色:红、绿、蓝,水果:苹果、香蕉}

const b={color:红、黑、蓝}

someFucntion(a,b);//结果{color:红,蓝}

考虑到可能有任意数量的键具有任意长度的数组的值。请帮我找到完美的解决方案。

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2020-06-25 11:05:30

我的一个同事给了我下面的函数,这正是我想要的。

代码语言:javascript
运行
复制
//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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62548857

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档