How to transform an array of arrays into an object with index signature?

So I have two types B and A, and an array a, which I should transform into type 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 = ???

I have no understanding how can I transform an array because of index signature [name: string] in type B. Usually I transform through array.map(value => {}), but here I can't find a way to include index signature in map method.

1 answer

  • answered 2021-10-24 13:44 pilchard

    B describes an object of the shape:

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

    but if you want an array of Bs you can

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

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum