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

如何从对象数组生成以id值为键的新对象数组?

解决方案

你的代码存在两个关键问题:

  • 参数解构错误:数组的每个元素是包含id属性的对象,而非键值对数组,不能用[key, value]来解构。
  • 箭头函数语法问题:直接写{key: value}会被解析为代码块而非对象字面量,导致返回undefined。

以下是正确的实现方式:

方法1:完整写法

const array = [
 {id: 'firstId'},
 {id: 'SecondId'},
 {id: 'ThirdId'}
];

const transformedArray = array.map(item => {
  // 使用动态属性名,把item.id的值作为对象的键
  return { [item.id]: null };
});

方法2:箭头函数简写(更简洁)

const array = [
 {id: 'firstId'},
 {id: 'SecondId'},
 {id: 'ThirdId'}
];

// 用圆括号包裹对象,避免被解析为代码块
const transformedArray = array.map(item => ({ [item.id]: null }));

执行后transformedArray的结果就是你期望的:

[
  {firstId: null},
  {SecondId: null},
  {ThirdId: null}
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 12:55:04