0

Suppose, I have two nested objects defined as:

let obj1={
   work:{
      title: "work",
      description: "All that is to be done.",
      view: 1
   },
   task:{
      title: "open"
   }
},
obj2={
   work:{
      title: "Work",
      view: null
   },
   person: "Aniruddha Sarkar"
},
obj3={
   task: "open"
};

What would be the most efficient function, say updateObj, which will produce the following results?

updateObj(obj1,obj2);

Output:

{
   work:{
      title: "Work",
      description: "All that is to be done."
   },
   task:{
      title: "open"
   },
   person: "Aniruddha Sarkar"
}

And,

updateObj(obj1,obj3);

Output:

{
   work:{
      title: "work",
      description: "All that is to be done.",
      view: 1
   },
   task:"open"
}
Aniruddha Sarkar
  • 1,903
  • 2
  • 14
  • 15
  • in obj3, is task a string by design? in updateObj, what trumps what? – Moshezauros Nov 17 '20 at 17:14
  • Well, there is no predefined design. The requirement in the example is, update the obj1 using the keys of obj3. If the corresponding key in either point to something other than an object, update the value in obj1 with obj 3, else if both are objects, update the nested object in obj1 in the same pattern with the corresponding nested object in obj3. – Aniruddha Sarkar Nov 17 '20 at 17:22
  • Check this thread on deep merge: https://stackoverflow.com/a/41474728/2109769 – Quercus Nov 17 '20 at 17:48
  • @Quercus, it just merges, and doesn't delete the keys with a null value. Furthermore, my requirement is anything other than object (like strings,arrays) to be completely replaced and not merged. – Aniruddha Sarkar Nov 17 '20 at 17:57

1 Answers1

0
function updateObj(a, b) {
    for (let [key, value] of Object.entries(b)) {
        if (typeof value === "object") {
            if (typeof a[key] === "object") {
                a[key] = {
                    ...a[key],
                    ...value
                };
            } else {
                a[key] = {
                    ...value
                };
            }
        } else {
            a[key] = value;
        }
    }
}

notice that if you don't want to use null values from the second object on the first one you will have iterate over the properties and only add values which are not null

Moshezauros
  • 2,493
  • 1
  • 11
  • 15