Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
119
rated 0 times [  120] [ 1]  / answers: 1 / hits: 51752  / 12 Years ago, fri, september 21, 2012, 12:00:00

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.


More From » object

 Answers
186
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.


[#82967] Thursday, September 20, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kinsley

Total Points: 352
Total Questions: 84
Total Answers: 94

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;