Search code examples
javascriptobjectpropertieskey

Updating JavaScript object-attributes from another object


I want to update an object that could look like this:

currentObject = {
    someValue : "value",
    myObject : {
        attribute1 : "foo",
        attribute2 : "bar"
    }
};

.. with an object that contains some changes i.e.:

updateObject = {
    myObject : {
        attribute2 : "hello world"
    }
};

At the end I would like to have currentObject updated so that:

currentObject.myObject.attribute2 == "hello world"

That should be posible for other objects as well.. As a solution I thought about iterating over the object and somehow take care of the namespace. But I wonder if there is an easy solution for that problem by using a library like jQuery or prototype.


Solution

  • function update(obj/*, …*/) {
        for (var i=1; i<arguments.length; i++) {
            for (var prop in arguments[i]) {
                var val = arguments[i][prop];
                if (typeof val == "object") // this also applies to arrays or null!
                    update(obj[prop], val);
                else
                    obj[prop] = val;
            }
        }
        return obj;
    }
    

    should do the trick: update(currentObject, updateObject). You might want to add some type checks, like Object(obj) === obj to extend only real objects with real objects, use a correct loop for arrays or hasOwnProperty tests.