如何在 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'}]}
基本上我想根据对象的键连接数组。
如何在 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'}]}
基本上我想根据对象的键连接数组。
你可以这样做:
for (var k in h2) {
h1[k]=(h1[k]||[]).concat(h2[k]);
}
结果对象将是 h1。
演示(打开控制台)
如果要保持 h1 不变,请执行以下操作:
h3 = {};
for (var k in h1) h3[k]=h1[k].slice();
for (var k in h2) h3[k]=(h3[k]||[]).concat(h2[k]);