-2

I've been working with JS + JSON, and I can't find a way to make a new object out of a value of some parent object. For example:

const parent = {
  "child": {"value": 12},
  "otherChild": {"value": 83}
}

// I want to create a duplicate without editing the original
const newChild = parent.child;
newChild.value = 25;

// Logs 25
console.log(parent.child.value);

I've tried using new Object(); and it still doesn't work. :/

Oliver
  • 23
  • 5
  • Does this answer your question? [Clone Object without reference javascript](https://stackoverflow.com/questions/12690107/clone-object-without-reference-javascript) – yeya Nov 30 '22 at 15:43

2 Answers2

3

The easiest way will be:

const parent = {
    "child": {"value": 12},
    "otherChild": {"value": 83}
}

// I want to create a duplicate without editing the original
const newChild = JSON.parse(JSON.stringify(parent.child));
newChild.value = 25;

If you don't need any old browsers \ node version support, you can also easily use:

const newChild = structuredClone(parent)

Both will work with sub objects too.

yeya
  • 1,968
  • 1
  • 21
  • 31
1

You can try using a lodash method called cloneDeep

const _ = require('lodash');
   
var obj = {
    x: 23
};
   
// Deep copy
var deepCopy = _.cloneDeep(obj);
   
console.log('Comparing original with'
    + ' deep ', obj === deepCopy);
   
obj.x = 10; // Changing original value
   
console.log('After changing original value');
   
console.log("Original value ", obj);
   
console.log("Deep Copy value ", deepCopy);

However there are also native solutions, check out this answer

mcnk
  • 1,690
  • 3
  • 20
  • 29