2012-10-26 77 views
3

我有2个json对象,我想合并。我试过使用concatmerge函数,但结果不是我想要的。任何帮助,将不胜感激。结合2个jsons对象

var jason1 = 
{ 
    "book1": { 
    "price": 10, 
    "weight": 30 
    }, 
    "book2": { 
    "price": 40, 
    "weight": 60 
    } 
}; 

,这是其他物体

var jason2 = 
{ 
    "book3": { 
    "price": 70, 
    "weight": 100 
    }, 
    "book4": { 
    "price": 110, 
    "weight": 130 
    } 
}; 

这就是我想要的东西:

var jasons = 
{ 
    "book1": { 
    "price": 10, 
    "weight": 30 
    }, 
    "book2": { 
    "price": 40, 
    "weight": 60 
    } 
    "book3": { 
    "price": 70, 
    "weight": 100 
    }, 
    "book4": { 
    "price": 110, 
    "weight": 130 
    } 
}; 
+0

那些不是JSON对象,它们只是对象。 JSON是一种将对象表示为字符串的方式(例如,通过网络传输)。 – Barmar

+0

[我怎样才能动态合并两个JavaScript对象的属性?](http://stackoverflow.com/questions/171251/how-can-i-merge-properties-of-two-javascript-objects-dynamically) –

回答

3

请参阅从的Prototype.js框架Object.extend方法的来源:

https://github.com/sstephenson/prototype/blob/master/src/prototype/lang/object.js#L88

function extend(destination, source) { 
    for (var property in source) { 
    destination[property] = source[property]; 
    } 
} 

用法然后...

extend(jason1, jason2); 

对象jason1现在包含正是你想要的。

+0

这肯定会工作,但我不认为它值得为此添加一个库,当它可以很容易地实现没有。 – prodigitalson

+0

我没有建议使用这个库,只是为了看看它的源代码('Object.extend'方法的实现)。 –

+0

啊,我看到原型,并认为你建议他添加库...我的坏。 – prodigitalson

0

你仅仅指刚需要他们,要手动循环:

var both = [json1, json2], 
    jasons = {}; 


for (var i=0; i < both.length; i++) { 
    for (var k in both[i]) { 
    if(both[i].hasOwnProperty(k)) { 
     jasons[k] = both[i][k]; 
    } 
    } 
} 

继承人的工作fiddle。您可能想要考虑如果存在重复键时会发生什么情况 - 例如,如果两个json对象中都存在book3,会发生什么情况。随着代码我提供的价值在第二个总是胜利。

0

这是一种方法,但我确信有更多优雅的解决方案。

var jason1 = { 
    "book1": { 
     "price": 10, 
     "weight": 30 
    }, 
    "book2": { 
     "price": 40, 
     "weight": 60 
    } 
}; 
var jason2 = { 
    "book3": { 
     "price": 70, 
     "weight": 100 
    }, 
    "book4": { 
     "price": 110, 
     "weight": 130 
    } 
}; 
var jasons = {}; 
var key; 
for (key in jason1) { 
    if (jason1.hasOwnProperty(key) && !(jasons.hasOwnProperty(key))) { 
     jasons[key] = jason1[key]; 
    } 
} 
for (key in jason2) { 
    if (jason2.hasOwnProperty(key) && !(jasons.hasOwnProperty(key))) { 
     jasons[key] = jason2[key]; 
    } 
} 
console.log(jasons);