开发者

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 }


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


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}


var o = { 'a':3, 'b': 5 };
var n = { 'a': 999, 'c': 10 };

for (var key in n){
    o[key]=n[key];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜