合并两个数组并赋值

时间:2017-07-05 22:35:27

标签: javascript arrays multidimensional-array mapreduce

如何合并两个数组并将数组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?

1 个答案:

答案 0 :(得分:1)

像这样使用mapreduce



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);