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

如何将含id的对象数组重构为以id为键的结构并存入数组?

解决方案

方法1:直接遍历生成目标数组

如果不需要中间过渡对象,可以直接遍历原数组,动态生成以id为键的结构并存入数组:

const originalArray = [
  {id: 'TestId', name: 'TestNameString', type: 'TestType'},
  {id: 'AnotherId', name: 'AnotherName', type: 'AnotherType'}
];

const resultArray = originalArray.map(item => {
  const { id, ...restProps } = item;
  return { [id]: restProps };
});

console.log(resultArray);
// 输出:
// [
//   { TestId: { name: 'TestNameString', type: 'TestType' } },
//   { AnotherId: { name: 'AnotherName', type: 'AnotherType' } }
// ]

方法2:先转键值对象再转数组

如果需要先得到一个以id为键的完整对象,再将其拆分为数组元素,可以这么做:

const originalArray = [
  {id: 'TestId', name: 'TestNameString', type: 'TestType'},
  {id: 'AnotherId', name: 'AnotherName', type: 'AnotherType'}
];

// 第一步:生成以id为键的对象
const idKeyedObj = originalArray.reduce((acc, item) => {
  const { id, ...rest } = item;
  acc[id] = rest;
  return acc;
}, {});

// 第二步:将键值对象转为目标数组
const resultArray = Object.entries(idKeyedObj).map(([key, value]) => ({ [key]: value }));

兼容ES5的传统写法

如果运行环境不支持ES6语法,用基础循环实现:

const originalArray = [
  {id: 'TestId', name: 'TestNameString', type: 'TestType'},
  {id: 'AnotherId', name: 'AnotherName', type: 'AnotherType'}
];

const resultArray = [];
for (let i = 0; i < originalArray.length; i++) {
  const current = originalArray[i];
  const newItem = {};
  newItem[current.id] = {
    name: current.name,
    type: current.type
  };
  resultArray.push(newItem);
}

内容的提问来源于stack exchange,提问作者1zz0

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 20:32:03