You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将二维数组转换为键数量和键名未知的对象?

问题:动态键名的二维数组转对象数组

我已经掌握了已知键数量和键名时,将二维数组转换为对象数组的方法,代码示例如下:

const myArray = [
  ['Rice', '$6', 'super market'],
  ['water', '$7', 'traditional market']
];

const myObj = myArray
  .map(([name, price, place]) => ({ name, price, place }));

console.log(myObj);

但现在需要实现同样的功能,且键的数量和键名未知。例如目标数组可能是:

const myArray = [
  ['Rice', '$6'],
  ['water', '$7']
];

或者:

const myArray = [
  ['Rice', '$6',"promotion"],
  ['water', '$7',"normal"]
];

同时我会有对应的键名数组,比如['name','price','promotion']。尝试把代码中的解构部分[name, price, place]替换为定义好的键名变量但未能成功,请问该如何实现?

解决方案

核心思路是遍历二维数组的每个子数组,将子数组的每个元素与键名数组中对应位置的键一一映射,构建成对象。以下是两种实用实现方式:

方法1:使用reduce构建对象

const keys = ['name', 'price', 'promotion'];
const myArray = [
  ['Rice', '$6', 'promotion'],
  ['water', '$7', 'normal']
];

const result = myArray.map(item => {
  return keys.reduce((obj, key, index) => {
    obj[key] = item[index];
    return obj;
  }, {});
});

console.log(result);

方法2:使用forEach循环构建对象

如果觉得reduce不够直观,也可以用更直白的循环方式:

const keys = ['name', 'price'];
const myArray = [
  ['Rice', '$6'],
  ['water', '$7']
];

const result = myArray.map(item => {
  const obj = {};
  keys.forEach((key, index) => {
    obj[key] = item[index];
  });
  return obj;
});

console.log(result);

为什么直接替换解构失败?

数组解构是按位置提取值并赋值给固定变量名,而非用数组元素作为对象键名。比如const [a,b] = [1,2]是把1赋值给变量a、2赋值给变量b,不会自动生成键为a、b的对象。上面的方法则是主动把键名数组的元素作为对象键,对应子数组元素作为值,完美适配动态键名的场景。

内容的提问来源于stack exchange,提问作者Trúc Quyền

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 10:50:37