Home > other >  Create a record based on elements in another array in one line
Create a record based on elements in another array in one line

Time:11-02

I have an array of required items and wanted to create a record based off of the elements in that array. Each key in the required array will have an empty array in the exist record. Basically, I want to do the code below in one line:

const required = ['firstName', 'lastName'];
const exist: Record<string, string[]> = {};
required.forEach((key) => this.exist[key] = []);

The exist record will look like this:

exist = {
    'firstName': [],
    'lastName': []
}

I'm sort of new to typescript and wanted to see if this is possible.

CodePudding user response:

You could do it like this:

const required = ['firstName', 'lastName'];
const exist = Object.fromEntries(required.map(key => [key, []]));
console.log(exist);

  • Related