Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying Javascript object attributes

Tags:

javascript

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.

like image 600
Shawn Mclean Avatar asked Jul 08 '11 05:07

Shawn Mclean


People also ask

How do you copy properties from one object to another object in JavaScript?

Object.assign() The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the modified target object.

How do I copy an attribute from one object to another?

assign is the standard way to copy properties from one object to another. It is often used for copying properties that are one-layer deep. (One-layer deep means there are no nested objects).

How do I copy a field from one object to another in JavaScript?

The Object. assign() function can be used to copy all enumerable own properties from one or more source objects to a target object. This function returns the target object to the newObject variable.

How can we copy object without mutating?

Similar to adding elements to arrays without mutating them, You can use the spread operator to copy the existing object into a new one, with an additional value. If a value already exists at the specified key, it will be overwritten.


4 Answers

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;
like image 117
aroth Avatar answered Oct 06 '22 11:10

aroth


Using Object.assign

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

reference (MDN)

Using JSON.parse and JSON.stringify;

var newObj = JSON.parse(JSON.stringify(jsonObj));
like image 35
Antonio Avatar answered Oct 06 '22 09:10

Antonio


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']);
like image 41
Ronan Quillevere Avatar answered Oct 06 '22 10:10

Ronan Quillevere


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

like image 45
chachan Avatar answered Oct 06 '22 09:10

chachan