简体   繁体   中英

How to merge arrays?

How to merge these two arrays using JavaScript:

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

Into this:

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

You can use a simple function.

Either by adding the key/values from b into a :

function merge(a, b) {
    for (var p in b[0]) {
      a[0][p] = b[0][p];
    }
    return a;
}

merge(a, b);

Or by using a native array function like reduce :

function merge2(a, b) {
    return b.reduce(function (el) {
        return el;
    }, a);
}

console.log(merge2(a, b));

DEMO

Just use the built-in Javascript Array .concat() method.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM