Home > Mobile >  How do I filter only common object values in Javascript
How do I filter only common object values in Javascript

Time:09-22

I want to filter out key value pairs which are common in both objects. There are two objects:

first = {a:3 , b:4}
second  = {a:5 , b:4}

I used the below code to solve this:

c = {}
for (const key of Object.keys(first)) {
    for( const k of Object.keys(second)){
        if ( key == k){
            if (first[key]==second[k]){
                c[key] = first[key]
            }
        }
    }
}

This works fine and gives me the output {b:4}, but for the below test input values I get empty object as the output, I am not sure how to check for values that are common but not equal.

first = {a: 3, b: {x:7}};
second = {a: 4, b: {x: 7, y: 10}}

Here the output should be:

{b: {x:7}}

CodePudding user response:

You could take a recursive approach for nested objects and check for common keys and common values or if both values are objects take the common values of the nested objects.

function getCommon(a, b) {
    const isObject = o => typeof o === 'object';

    return Object.fromEntries(Object
        .keys(a)
        .filter(Set.prototype.has, new Set(Object.keys(b)))
        .filter(k => a[k] === b[k] || isObject(a[k]) && isObject(b[k]))
        .map(k => [k, isObject(a[k]) ? getCommon(a[k], b[k]) : a[k]])
    );
}

console.log(getCommon({ a: 3, b: { x: 7 } }, { a: 4, b: { x: 7, y: 10 } }));

  • Related