【问题标题】:How to transform an array of arrays into an object with index signature?如何将数组数组转换为具有索引签名的对象?
【发布时间】:2021-12-10 07:11:11
【问题描述】:

所以我有 B 和 A 两种类型,以及一个数组 a,我应该将其转换为 B 类型。

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 = ???

由于类型 B 中的索引签名 [name: string],我不明白如何转换数组。通常我通过 array.map(value =&gt; {}) 进行转换,但在这里我找不到在 map 方法中包含索引签名的方法。

【问题讨论】:

    标签: javascript arrays typescript ecmascript-6


    【解决方案1】:

    B 描述了一个对象的形状:

    export const b: B = {
      name1: {
        name: 'name1',
        age: 10,
        city: 'city1'
      }
    };
    

    但是如果你想要一个Bs 的数组,你可以

    export const b: B[] = a.map(([name, age, city]) => ({ [name]: { name, age, city } }));
    

    【讨论】:

      猜你喜欢
      • 2017-11-07
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 1970-01-01
      相关资源
      最近更新 更多