问题
I have two arrays and I want to merge the values of the two arrays into a single array, but both arrays have different values.
Example:
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" }
];
I tried this it, will work fine when data1 is unique, but the problem is when data1 is repeating it merges the first value:
var data = _.map(arr1, function(item){
return _.extend(item, _.findWhere(arr2, { dataid: item.dataid }));
});
回答1:
You can use map()
and merge the properties of first and second array on same index.
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"} ];
const res = arr1.map((x,i) => ({...x,...arr2[i]}));
console.log(res)
来源:https://stackoverflow.com/questions/56269352/merge-two-arrays-by-index-value-by-different-value-in-the-array