Reputation: 271744
var old = { 'a':3, 'b': 5 }
var new = { 'a': 999, 'c': 10 }
how do I append the "new" to the "old" and result in:
{ 'a': 999, 'b': 5, 'c': 10 }
Upvotes: 3
Views: 4229
Reputation: 79
jQuery provide a better function call $.extend. For example:
var old_obj = {'a': 3, 'b': 5};
var new_obj = {'a': 999, 'c': 10};
var result = $.extend(old_obj, new_obj);
The result will be
{a: 999, b: 5, c: 10}
Upvotes: 4
Reputation: 659
If you're using a framework most have a function that will do it, e.g jQuery's extend. Otherwise if you're using JavaScript with no framework you'd have to do it yourself.
You could do it using a for...in loop.
for(var key in newObject)
{
if(!newObject.hasOwnProperty(key)) {
continue;
}
oldObject[key] = newObject[key];
}
As a side note don't call vars "new" its a keyword in more than a few languages. Np if its just for the example. I've renamed it in my example from new to newObject upon suggestions from the comments.
Psts right, needed to check in the for...in loop the var was actually new's
Upvotes: 5
Reputation: 93030
var o = { 'a':3, 'b': 5 };
var n = { 'a': 999, 'c': 10 };
for (var key in n){
o[key]=n[key];
}
Upvotes: 1