How to create deep object with dynamic name in Javascript?

What are good ways to create a copy of an object in javascript?

  • I need to create a copy of a JSON object. Methods like Object.create(), new Object() didnt help me. the new objects created using these methods always takes the reference of the original object

  • Answer:

    I've developed quite a few webapps and I must tell you that I only wanted to copy entire json objects when I was a beginner. There are very few cases when you actually have to do this. If you are using jquery, $.extend with a recursive parameter set to true will do the trick. Basically you have to iterate over each key in the json object, and if the key is a primitive type just copy that value with normal attribution (=). If the key is an object itself assign to the key of the resulting object the result of calling the same copy function again on the sub object that you are iterating over. This is a pretty boring code. Jquery and extjs offer the extend method for this.

Vlad Nicula at Quora Visit the source

Was this solution helpful to you?

Other answers

ES6 feature Object.prototype.assign() It is used to copy all of the "own" properties from source object(s) on to a target object. So it won't copy any properties that are inherited from an object's prototype. Usage: let sourceObj = { a: 12, b(x) { return x *x }, c: "Some string" } let targetObj = {}; let clone = Object.assign({}, sourceObj); console.log(targetObj === clone); // true https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

Ryan Tomczik

boring code: function clone(obj) { if (null == obj || "object" != typeof obj) return obj; var copy = obj.constructor(); for (var attr in obj) { if (obj.hasOwnProperty(attr)) { if (Object.getOwnPropertyDescriptor(obj, attr).value instanceof Object) { copy[attr] = clone(obj[attr]); } else { Object.defineProperty(copy, attr, Object.getOwnPropertyDescriptor(obj,attr)); } } } return copy; }

Cai Yiheng

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.