如何使用JavaScript合并这两个数组:
[{"id1":"value1","id2":"value2"}]
[{"id3":"value3","id4":"value4"}]
进入这个:
[{"id1":"value1","id2":"value2","id3":"value3","id4":"value4"}]
答案 0 :(得分:0)
您可以使用简单的功能。
将b
中的键/值添加到a
:
function merge(a, b) {
for (var p in b[0]) {
a[0][p] = b[0][p];
}
return a;
}
merge(a, b);
或者使用像reduce
这样的原生数组函数:
function merge2(a, b) {
return b.reduce(function (el) {
return el;
}, a);
}
console.log(merge2(a, b));
答案 1 :(得分:-1)
只需使用内置的Javascript Array .concat()方法。
http://www.w3schools.com/jsref/jsref_concat_array.asp
var a = ["id1","value1","id2","value2"]
var b = ["id3","value3","id4","value4"]
var c = a.concat(b)
//c is now ["id1","value1","id2","value2","id3","value3","id4","value4"]