如何在javascript中合并这两个对象?
h1 = {12: [{actor: 'wayne'}, {actor: 'bill'}], 13: [{actor: 'james'}]}
h2 = {13: [{actor: 'mark'}]}
得到:
result = {12: [{actor: 'wayne'}, {actor: 'bill'}], 13: [{actor: 'james'}, {actor: 'mark'}]}
基本上我想根据对象的键来连接数组。
答案 0 :(得分:5)
你可以这样做:
for (var k in h2) {
h1[k]=(h1[k]||[]).concat(h2[k]);
}
结果对象为h1。
Demonstration(打开控制台)
如果您想保持h1不变,请执行以下操作:
h3 = {};
for (var k in h1) h3[k]=h1[k].slice();
for (var k in h2) h3[k]=(h3[k]||[]).concat(h2[k]);