我想要组合2个json对象。我尝试使用concat
和merge
函数,但结果不是我想要的。任何帮助将不胜感激。
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 :(得分: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
现在包含您想要的内容。
答案 1 :(得分: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
,那该怎么办?使用我提供的代码,第二个中的值总是获胜。
答案 2 :(得分: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);