Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a javascript object to an existing javascript object?

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 }
like image 471
TIMEX Avatar asked Jul 15 '26 08:07

TIMEX


1 Answers

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

like image 56
Steve Elliott Avatar answered Jul 17 '26 19:07

Steve Elliott



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!