javascriptjsonnested-objectobject-comparison

Copy values from nested object to another


I have a two nested objects that I want to compare with each other.

obj1 is the new structure that I need.

obj2 is the old structure that I'm comparing with and has the values I need.

Basically what I'm trying to achieve here is the following:

If a key from obj1 exists in obj2 take the value.

for example:

let obj1 = {
 a: 10,
 c: {
   d: 30,
   e: 50,
 },
};

let obj2 = {
 a: 100,
 x: 200,
 c: {
   e: 300,
   y: 400,
 },
};

should result in

result = {
 a: 100,
 c: {
  d: 30,
  e: 300,
 }
}

I'm having a hard time setting up a recursive function for this problem.

I've read the documentation on lodash library, but there is not function thats specificly solves this problem.


Solution

  • You can use the reduce method, over Obj1 keys. Check if the key is in Obj2 then add new property to the carry value of the reducer. Initialized with {}

    const obj1 = {
      a: 10,
      c: {
        d: 30,
        e: 50,
      }
    };
    
    const obj2 = {
      a: 100,
      x: 200,
      c: {
        e: 300,
        y: 400,
      }
    };
    
    const hasProp = Object.prototype.hasOwnProperty
    const newObj = Object.keys(obj1).reduce((obj, currentKey) => {
        obj[currentKey] = hasProp.call(obj2, currentKey) ? obj2[currentKey] : obj1[currentKey];
        return obj;
    }, {})
    
    console.log(newObj)