1

I have a use case in which I need to copy the whole object data to another object without creating an inner object. i.e, object inside the object.

For example,

obj_1 = {
       "_id": "SPool",
       "w1": 60,
       "w2": 150
     }

obj_2 = {
        "_id": "SPool",
        "w1": 30,
        "w2": 120
      }

As both objects having same _id fields, I want to copy the data of obj-2 to obj-1 and want to find the difference between the 2 objects like the following.

obj_1 = {
       "_id": "SPool",
       "w1": 60,
       "w2": 150,
       "obj_2" : {
                   "w1": 30,
                   "w2": 120
                 }
       "diff": {
                 "w1": 30,
                 "w2": 30
               }
     }

Is it possible to do like this?

Aravind
  • 424
  • 3
  • 19

1 Answers1

2

You should be able to use Array.reduce, Object.entries etc. to create the new, merged object from the "parent" objects.

obj_1 = {
       "_id": "SPool",
       "w1": 60,
       "w2": 150
     }

obj_2 = {
        "_id": "SPool",
        "w1": 30,
        "w2": 120
      }
      
 function mergeObjects(obj_1, obj_2, propertyName) {
     let merged = { ...obj_1 };
     merged[propertyName] = obj_2;
     merged.diff = Object.entries(obj_1).reduce((acc, [key, value]) => { 
         if (obj_2[key] && typeof obj_2[key] === "number") { 
             acc[key] = value - obj_2[key];
         }
         return acc;
     }, {});
     return merged;
 }
 

 console.log("Merged objects:", mergeObjects(obj_1, obj_2, "obj_2"));
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
  • 1
    I don't know to which extent this is important for OP, but he specifies ```obj_1``` to be modified, which here is not the case, ```obj_1``` is left intact. – grodzi Feb 10 '20 at 11:12
  • 1
    HI @grodzi, thank you very much for the comment. You're right that we do not modify obj_1, rather we clone it and assign obj2 as a child of the cloned object. I rather think that in general this is a better pattern, i.e, effectively immutable objects. But you could easily change this behaviour by replacing let merged = { ...obj_1 } with let merged = obj_1. – Terry Lennox Feb 10 '20 at 11:16