如何合并数组?

时间:2015-07-30 17:33:18

标签: javascript arrays merge

如何使用JavaScript合并这两个数组:

[{"id1":"value1","id2":"value2"}]
[{"id3":"value3","id4":"value4"}]

进入这个:

[{"id1":"value1","id2":"value2","id3":"value3","id4":"value4"}]

2 个答案:

答案 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));

DEMO

答案 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"]