cloning a new object from existing in javascript

javascript copy object without reference
clone object java
javascript clone array
javascript clone function
javascript object assign
deep clone javascript
javascript clone string
es6 clone object

I have a multi step javascript object like this:

const source = {
  prev: [],
  current: {
    list: [{ a: 1, b: 2, c: 3 }],
    data: [{ c: 1, b: 2 }]
  },
  id: 12,
  next: []
};

and I would like to create a fresh copy of it. I know if I use something like let copy = { ...source }; it's like a shallow copy. So if i change those arrays or objects in source they will also change in copy.

Is there anyway that by de-structuring, I get a fresh copy of all items? or should I do it manually for each and every level deep like this:

copy.prev = [...source.prev]
copy.current.list = [...source.current.list]
copy.current.data= [...source.current.data]

and so on

There's an old way to do it, but still works:

var cloned = JSON.parse(JSON.stringify(original));

3 Ways to Clone Objects in JavaScript, Cloning an object in JavaScript a task that is almost always used in any project, to clone everything from simple objects to the most complicated  Using spread will clone your object. Note this will be a shallow copy. As of this post, the spread operator for cloning objects is in Stage 4. So it's not officially in the specifications yet. So if you were to use this, you would need to compile it with Babel (or something similar).

You can use JSON.stringify

    const source = {
  prev: [],
  current: {
    list: [{ a: 1, b: 2, c: 3 }],
    data: [{ c: 1, b: 2 }]
  },
  id: 12,
  next: []
};

newObj = JSON.parse(JSON.stringify(source));

3 Ways to clone objects in JavaScript - Better Programming, The obj variable is a container for the new object initialized. without any reference and there exist a source property whose value is an object  The cloneNode() method creates a copy of a node, and returns the clone. The cloneNode() method clones all attributes and their values. Tip: Use the appendChild() or insertBefore() method to insert the cloned node to the document. Tip: Set the deep parameter value to true if you want to clone all descendants (children), otherwise false.

You can deconstruct like this:

const source = {
  prev: [],
  current: {
    list: [{ a: 1, b: 2, c: 3 }],
    data: [{ c: 1, b: 2 }]
  },
  id: 12,
  next: []
};

const {
current: {list: listClone, data: dataClone}
} = source

console.log(listClone, dataClone)

Copying Objects in JavaScript ― Scotch.io, Diffrent methods to copy javascript object. In this case your old and new object both will point to the same memory address. Any change in either object will or you can write your own function to do the deep copy/cloning. The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object. It returns the target object. The source for this interactive example is stored in a GitHub repository.

With a simple object containing objects, arrays, and primitives, it's not that much code just to recursively clone everything.

Just return the primitives, map() the arrays, and reduce the object keys passing the values back in. Something like:

const source = {prev: [],current: {list: [{ a: 1, b: 2, c: 3 }],data: [{ c: 1, b: 2 }]},id: 12,next: []};

function clone(obj){
    return (typeof obj == 'object')
        ? (Array.isArray(obj))
            ? obj.map(i => clone(i)) 
            : Object.entries(obj).reduce((o, [key, value]) => 
              Object.assign(o, {[key]: clone(value)}), {})  
        : obj

}

let a_clone = clone(source)
console.log(JSON.stringify(a_clone, null, 2))


// is the clone deep? should be false
console.log(a_clone.prev === source.prev)
console.log(a_clone.current.list === source.current.list)

Different methods to copy an object in JavaScript, The Object.assign() method copies all enumerable own properties from one This may make it unsuitable for merging new properties into a prototype For deep cloning, we need to use alternatives, because Object.assign()  objCopy object has a new Object.prototype method different from the mainObj object prototype method, which is not what we want. We want an exact copy of the original object. Property descriptors are not copied. A "writable" descriptor with value set to be false will be true in the objCopy object. The code above only copies enumerable properties of mainObj.

Object.assign(), Cloning in javascript is nothing but copying an object properties to another object so as to avoid creation of an object that already exists. There are a 1) Iterating through each property and copy them to a new object. 2) Using  If an object or array contains other objects or arrays, shallow copies will work unexpectedly, because nested objects are not actually cloned. For deeply-nested objects, a deep copy will be needed.

How to clone an object in JavaScript?, Cloning a JavaScript object is a task that is used mostly because we do not want to create the same object if the same object already exists. There are few ways. By iterate through each property and copy them to new object. Using JSON  The Object.create() method creates a new object, using an existing object as the prototype of the newly created object. To understand the Object.create method, just remember that it takes two parameters. The first parameter is a mandatory object that serves as the prototype of the new object to be created.

How to clone a JavaScript object?, To shallow copy, an object means to simply create a new object with the exact same lodash.clone() We would like to use assign whenever there is a need to assign some new properties to an existing object, for example: The Object.entries() method will only return the object instance’s own properties, and not any properties that may be inherited through its prototype. Object.assign() Object.assign() is used to copy values from one object to another. We can create two objects, and merge them with Object.assign().

Comments
  • Guess I understood the question wrong. Why don't you just clone the original and keep it as a reference? And do updates in the original later? Why do you need all the levels separated?
  • In a nutshell, I have a multi level object that includes other objects and arrays as properties, I want to have a new copy of this object where all items are new copies not references.
  • Then my answer was correct.
  • Thanks, I forgot about this simple solution. LOL