如何合并两个数组并将数组B中的值分配给数组a [x]中的所有数组,如下所示:
var areas = [];
var values = [];
values[0] = "aaa";
values[1] = "bbb";
areas[0] = ["A","B","C"];
areas[1] = ["D","E","F"];
,预期值为:
array_three[0] = ["A" => "aaa","B" => "aaa", "C" => "aaa"];
array_three[1] = ["D" => "bbb","E" => "bbb", "F" => "bbb"];
我是否必须使用map或forEach?
答案 0 :(得分:1)
像这样使用map
和reduce
:
var areas = [
["A","B","C"],
["D","E","F"]
];
var values = ["aaa", "bbb"];
var result = values.map(function(value, i) {
return areas[i].reduce(function(obj, area) {
obj[area] = value;
return obj;
}, {});
});
console.log(result);

或者很快使用ES6的箭头功能:
var areas = [
["A","B","C"],
["D","E","F"]
];
var values = ["aaa", "bbb"];
var result = values.map((value, i) => areas[i].reduce((obj, area) => (obj[area] = value, obj), {}));
console.log(result);