通过索引值按数组中的不同值合并两个数组

时间:2019-05-23 06:39:36

标签: javascript arrays array-merge array-combine

我有两个数组,我想将两个数组的值合并为一个数组,但是两个数组都有不同的值。

示例:

var arr1 = [
            { data1: 1 ,data2: "value1"},
            { data1: 1 ,data2: "value2"},
            { data1: 2, data2: "value3"},
            { data1: 3 ,data2: "value3"},
            { data1: 3 ,data2: "value3"}
          ];
var arr2 = [
            { data1:1, data3:"val1"}, 
            { data1: 1, data3: "val2"},
            { data1: 2, data3: "val1"},
            { data1: 3, data3: "val1"},
            { data1: 3, data3: "val2"}
           ]; 
var arr3 = [
             { data1:1, data2: "value1", data3:"val1"}, 
             { data1: 1, data2: "value2", data3: "val2"},
             { data1: 2, data2: "value3", data3: "val1"},
             { data1: 3, data2: "value3", data3: "val1" },
             { data1: 3, data2: "value3", data3: "val2" }
           ];

我尝试过此操作,当data1唯一时可以正常工作,但是问题是当data1重复时它合并了第一个值:

var data = _.map(arr1, function(item){
                return _.extend(item, _.findWhere(arr2, { dataid: item.dataid }));
           });

1 个答案:

答案 0 :(得分:0)

您可以使用 Contents in 2 collections are not equal 并在同一索引上合并第一个和第二个数组的属性。

import {
    Dropbox
} from "dropbox";

const dbx = new Dropbox({
    accessToken: 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX',
    fetch
})

dbx.filesListFolder({
    path: ''
}).then(res => console.log(res))