Home > front end >  How to transform an array of arrays into an object with index signature?
How to transform an array of arrays into an object with index signature?

Time:10-24

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.

CodePudding user response:

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 } }));
  • Related