Copy Javascript Object Attributes

I have 1 object coming from a server with several properties in which I want to remove it into a new object, changing the name of property 1 and saving the rest.

the code:

JSON: { UserId: 1, Name: "Woo", Age: 10 }

The format of the object in which I want:

 var newObj = {} newObj.id = jsonObj.UserId; //Everything property below here is the same. How can i prevent writing this code? newObj.Name = jsonObj.Name; newObj.Age = jsonObj.Age; 

What I'm doing is based on this answer , trying to parse some json in a format that requires me to change the name of property 1.

+9
source share
6 answers

In such a simple case, you can do something like:

 var newObj = {id: jsonObj.UserId, Name: jsonObj.Name, Age: jsonObj.Age}; 

For a more complex object with a lot of fields, you might prefer something like:

 //helper function to clone a given object instance function copyObject(obj) { var newObj = {}; for (var key in obj) { //copy all the fields newObj[key] = obj[key]; } return newObj; } //now manually make any desired modifications var newObj = copyObject(jsonObj); newObj.id = newObj.UserId; 
+15
source

If you want to copy only certain fields

  /** * Returns a new object with only specified fields copied. * * @param {Object} original object to copy fields from * @param {Array} list of fields names to copy in the new object * @return {Object} a new object with only specified fields copied */ var copyObjectFields = function (originObject, fieldNamesArray) { var obj = {}; if (fieldNamesArray === null) return obj; for (var i = 0; i < fieldNamesArray.length; i++) { obj[fieldNamesArray[i]] = originObject[fieldNamesArray[i]]; } return obj; }; //example of method call var newObj = copyObjectFields (originalObject, ['field1','field2']); 
+3
source

I prefer to reuse instead of recreating, so I suggest http://underscorejs.org/#clone

+3
source

I do not understand your question, but this is what I usually do when I extract from an existing object:

 var newObj = new Object(jsonObj); alert(newObj.UserId === jsonObj.UserId); //returns true 

Is that what you asked? Hope this helps.

+1
source
 function clone(o) { if(!o || 'object' !== typeof o) { return o; } var c = 'function' === typeof o.pop ? [] : {}; var p, v; for(p in o) { if(o.hasOwnProperty(p)) { v = o[p]; if(v && 'object' === typeof v) { c[p] = clone(v); } else { c[p] = v; } } } return c; } 
+1
source

Using Object.assign

 var newObj = Object.assign({}, jsonObj); 

reference (MDN)

Using JSON.parse and JSON.stringify;

 var newObj = JSON.parse(JSON.stringify(jsonObj)); 
0
source

All Articles