Search code examples
javascriptnode.jsjsonobject

How can I create a new Object from a JSON value without changing the parent in JS?


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. :/


Solution

  • 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.