0

I have assigned some data to the one object and I want that object in future as it was like the first time. Whenever I do changes for the parent object it is getting reflected in the child object too. How can I solve this? Please give all possible answer for the object, arrays, maps also.

var parentObject = someData;
const childObj = Object.assign({}, parentObject);

I want to change only parent object and I want to keep child object as constant to use in the future.

MH2K9
  • 11,951
  • 7
  • 32
  • 49
Pavankumar AN
  • 55
  • 1
  • 12

1 Answers1

1

You can write a method to check weather an Object is frozen or not. Here is an example where I merged parent and child object and then freeze the child object. Again If call the mergeObject() to merge the parent and child, nothing is merged. Since we freeze the child object after first merge.

/**
 * Merge two object using Object.assign()
 * @param parentObj
 * @param childObj
 * @returns {ReadonlyArray<any>} returns frozen object
 */
function mergeObject(parentObj, childObj) {
   return Object.isFrozen(childObj) ? childObj : Object.freeze(Object.assign({}, parentObj))
}

// Before freezing
var parentObject = {a: 4};
var childObj = mergeObject(parentObject, {});
console.log(childObj); // {a: 4}

// After freezing
parentObject.b = 6;
childObj = mergeObject(parentObject, childObj);
console.log(childObj); // {a: 4}, didn't merge {b: 6}
MH2K9
  • 11,951
  • 7
  • 32
  • 49