Copying Javascript object attributes

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']);

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;

Tags:

Javascript