如何组合2个数组,在Javascript中具有相同的值

时间:2017-02-13 23:55:29

标签: javascript arrays object arraylist

我有阵列

 var array1 = [
    {"id" : 1,"val1" : 1,"val2": 1},
    {"id" : 2,"val1" : 2,"val2": 1},
    {"id" : 3,"val1" : 0,"val2": 0}
 ];

 var array2 = [
    {"id" : 1,"val1" : 1,"val3": 1},
    {"id" : 2,"val3": 1},
    {"id" : 3,"val3": 0}
 ];

我希望输出像这样

 var array3 = [
   {"id" : 1,"val1" : 1,"val2": 1, "val3" : 1},
   {"id" : 2,"val1" : 2, "val3" : 1},
   {"id" : 3,"val1" : 0, "val3" : 0}
 ];

是否有简单的(r)快捷方式?谢谢!

1 个答案:

答案 0 :(得分:3)

您可以使用.map()Object.assign()

var array3 = array1.map(function(o, i) {
               return Object.assign({}, array2[i], o)
             })