11

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

Code:

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

The format of the object I want it in:

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 into a format that requires me to change the name of 1 property.

Community
  • 1
  • 1
Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

6 Answers6

17

For such a simple case, you could do something like:

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

For a more complex object with a large number 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;
aroth
  • 54,026
  • 20
  • 135
  • 176
  • Hey, nice. Is this function "Deep copy", does it work with inner objects that jsonObj has set as properties? – Stephane Gosselin Jul 08 '11 at 05:53
  • @stefgosselin - No, it is not a proper deep copy implementation. That would require recursing through any `Array` and `Object` fields in the object. If the object being copied contains any such fields, this method only creates a shallow copy of the nested objects/arrays. – aroth Jul 08 '11 at 06:10
4

If you want to copy only specific 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']);
Ronan Quillevere
  • 3,699
  • 1
  • 29
  • 44
3

I mostly prefer to reuse instead of recreate so I'd suggest http://underscorejs.org/#clone

chachan
  • 2,382
  • 1
  • 26
  • 41
1

Using Object.assign

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

reference (MDN)

Using JSON.parse and JSON.stringify;

var newObj = JSON.parse(JSON.stringify(jsonObj));
Antonio
  • 851
  • 2
  • 8
  • 17
1
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;
}
Evgeniy Timchenko
  • 129
  • 1
  • 5
  • 14
0

Dont really understand your question, but this is what I normally do when I extract from an existing object:

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

Is that what you were asking? Hope that helps.

Benny Tjia
  • 4,853
  • 10
  • 39
  • 48
  • +1 Nice tip. Just to be sure, JS not my main language, `newObj` _would be a copy of jsonObj and not a reference where changing value in jsonObj won't affect newObj ? .. I should of slapped this in fiddle but too lazy. heh :) – Stephane Gosselin Jul 08 '11 at 05:48
  • It will be a copy, and you always access the read/write attribute using newObj.Id. If you change the attributes using .prototype, then it will change the values in the base class :) – Benny Tjia Jul 08 '11 at 05:57
  • 4
    I like this solution for its conciseness, but it comes with an important caveat: `newObj` and `jsonObj` will refer to the same object. So changing a field in one causes the same change to appear in the other. Here's an example demonstrating this: http://jsfiddle.net/3JvAd/ – aroth Jul 08 '11 at 06:06
  • @aroth Nice demo. So what is the way to do a deep copy? Is it `assign` ? – WestCoastProjects Jul 09 '20 at 19:29
  • I have downvoted since the code is doing a shallow copy which is not what the OP were likely intending – WestCoastProjects Jul 09 '20 at 19:30