Solve the problem using spread operator

 Question:

Change the value of m inside the obj using spread operator. 

let obj = {
  g: 5,
  h: {
    i: 6,
    j: 7,
    k: {
      l: 8,
      m: 9,
    },
  },
};

 

Answer:

let objNew = { ...obj, h: { ...obj.h, k: { ...obj.h.k, m: 10 } } };
console.log(objNew);

// Output:{ g: 5, h: { i: 6, j: 7, k: { l: 8, m: 10 } } }

 

Explanation: 

  1. Spread Operator: It copies the properties of an object into a new object.
  2. Step-by-Step:
    • { ...obj } creates a shallow copy of obj.
    • { ...obj.h } creates a shallow copy of the h object inside obj.
    • { ...obj.h.k } creates a shallow copy of the k object inside h.
    • Finally, you set the value of m to 10 in the copied k object.