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

如何将给定嵌套数组转换为键值对应的对象数组(array of objects)

实现方法(JavaScript 环境)

核心逻辑

原数组的每一项都包含两个子数组,第一个是属性名集合,第二个是属性值集合,只需按索引配对两组数组的元素生成对象,同时将id字段从字符串转为数字类型即可得到预期结果。

基础实现代码

const original = [ 
  [ [ 'id', 'name' ], [ '1', 'A' ] ],
  [ [ 'id', 'name' ], [ '2', 'B' ] ],
  [ [ 'id', 'name' ], [ '3', 'C' ] ]
];

const output = original.map(item => {
  const [keys, values] = item;
  const temp = {};
  keys.forEach((key, idx) => {
    temp[key] = key === 'id' ? Number(values[idx]) : values[idx];
  });
  return temp;
});

console.log(output); // 符合预期输出结果

简写版本

可以用Object.fromEntries简化键值对拼接的逻辑:

const output = original.map(([keys, values]) => {
  const obj = Object.fromEntries(keys.map((k, i) => [k, values[i]]));
  obj.id = Number(obj.id);
  return obj;
});

内容的提问来源于stack exchange,提问作者mohamed ali

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:24:08