【问题标题】:How can we extract intersecting key and its intersecting values of 2 objects in JS?我们如何在 JS 中提取 2 个对象的相交键及其相交值?
【发布时间】:2020-06-24 06:18:39
【问题描述】:

例如:

const a={color:[red,green,blue],fruits:[apple,banana]}

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

一些函数(a,b); //结果{颜色:[红色,蓝色]}

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

谢谢。

【问题讨论】:

    标签: object intersection


    【解决方案1】:

    我的一位同事给了我以下功能,这正是我想要的。

    //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;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-08-20
      • 2012-10-19
      • 2014-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多