将数组转换为具有预定义键的映射

Convert array to map with predefined keys

我有一个数组中的数据,如下所示:

let data = {[val1, val2, val3], [val4, val5, val6]}

我需要将其转换为具有预定义键的地图:

let keys = [key1, key2, key3]

我希望我的输出是这样的键值映射:

0: {key1:value1, key2:value2, key3:value3}
1: {key1:value4, key2:value5, key3:value6}

我试过:

let obj = Object.assign(keys, data)

但输出是:

0: (3) [value1, value2, value3]
1: (3) [value4, value5, value6]

简单的解决方案。

let data = [
  [1, 2, 3],
  [4, 5, 6]
];
let keys = ["key1", "key2", "key3"];

const res = data.map(([v1, v2, v3]) => {
  return {
    [keys[0]]: v1,
    [keys[1]]: v2,
    [keys[2]]: v3
  };
});

console.log(res);
// Also
const res2 = data.map(arr => {
  let map = {};
  keys.forEach((key, index) => {
    map[key] = arr[index];
  });
  return map;
});
console.log(res2);
// Also
const res3 = data.map(arr =>
  keys.reduce((o, key, index) => {
    o[key] = arr[index];
    return o;
  }, {})
);
console.log(res3);
.as-console-wrapper { max-height: 100% !important; top: 0; color: blue; background: #fff}

您可以使用 .map() and .reduce() 函数来获得所需的输出:

let data = [['val1', 'val2', 'val3'], ['val4', 'val5', 'val6']];
let keys = ['key1', 'key2', 'key3'];

let result = data.map(
  vals => vals.reduce((r, c, i) => (r[keys[i]] = vals[i], r), {})
);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

使用Object.fromEntries和映射

const data = [
  [1, 2, 3],
  [4, 5, 6]
];
const keys = ["key1", "key2", "key3"];

const updated = data.map(arr =>
  Object.fromEntries(arr.map((item, i) => [keys[i], item]))
);

console.log(updated);