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

如何在TypeScript中将二维数组转为带索引签名的对象

实现方案

你需要的是将数组聚合为对象,不能用Array.map()(该方法只能返回数组),可以使用Array.reduce()完成转换,完整实现如下:

type A = Array<[string, number, string]>;

type B = {
    [name: string]:
        {
            name: string,
            age: number,
            city: string
        }
}

const a: A = [
    ['name1', 10, 'city1'],
    ['name2', 33, 'city2'],
    ['name3', 61, 'city3'],
    ['name4', 60, 'city4']
];

export const b: B = a.reduce((accumulator, currentItem) => {
  // 解构数组当前项的三个字段
  const [name, age, city] = currentItem;
  // 以name为键,对应结构为值写入聚合对象
  accumulator[name] = { name, age, city };
  return accumulator;
// 初始值设为空对象,用类型断言指定为B类型避免TS报错
}, {} as B);

补充说明

类型B中的[name: string]是索引签名,意思是该类型的对象允许任意字符串为键,且键对应的值必须符合{name: string, age: number, city: string}的结构,上述代码中我们直接把数组每项的第一个元素作为键写入对象,完全匹配该类型要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 15:09:03