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

如何用Array.map将对象数组转换为索引签名类型?

问题与解决方法

问题

给定对象数组:

let items = [
    { id: 1, name: 'one'},
    { id: 2, name: 'two'},
    { id: 3, name: 'three'},
];

需要将其转换为如下索引签名类型的对象:

let result: {[key: number]: string};

尝试使用Array.prototype.map转换时写法错误,无法得到正确结果:

result = array.map(elem => {[key: elem.id]: elem.name});

解决思路与代码

首先明确:Array.prototype.map的返回值是数组,而我们需要的是单个对象,直接用map无法直接得到目标结果,推荐以下两种方法:

方法一:使用reduce(更高效)

reduce可以直接累加构建目标对象,是最适配的方式:

const result: {[key: number]: string} = items.reduce((acc, elem) => {
    acc[elem.id] = elem.name;
    return acc;
}, {} as {[key: number]: string});

也可以写成更简洁的形式:

const result = items.reduce((acc, { id, name }) => ({ ...acc, [id]: name }), {} as {[key: number]: string});

方法二:结合map和Object.fromEntries

如果一定要用到map,可以先将数组转为键值对格式的数组,再用Object.fromEntries转换为对象:

const result: {[key: number]: string} = Object.fromEntries(
    items.map(elem => [elem.id, elem.name])
);

原写法错误原因

  1. map返回值是数组,无法直接赋值给对象类型的result;
  2. 对象字面量动态属性语法错误:动态属性应直接写[elem.id],不需要key:标注;且箭头函数直接返回对象时,需要用括号包裹,否则会被解析为函数体。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 09:32:53