简体   繁体   中英

How to create a Javascript/Typescript Map dynamically without for loop?

I want to dynamically create a Typescript Map<string, Person> object where Person is a class.

I can use for loop to create a map like this:

function getInitializedPersonMap(size){
  const personMap = new Map<string, Person>();
  for (let index = 0; index < size; index++) {
    personMap.set(index.toString(), {} as Person);
  }
  return personMap;
}

However, I am trying to build a habit of moving away from 'for' loops and use functions like map, filter, reduce.

My attempt without loop looks like this which is not quite as readable as one with for loop:

function getInitializedPersonMap(size){
   return new Map<string, Person>(
      Array.from(new Array(size), (_, index) => [
        index.toString(),
        {} as Person,
      ])
    );
}

For scenarios like this is this an overkill to avoid 'for' loops?

You can use Map , notice the type has been explicitly mentioned.

var result = sizeArr.map((i): [string, Person] => [i, {} as Person]);

As @VLAZ mentioned that size is an number, so use Array.from to flatten the array from target size.

let sizeArr = Array.from(Array(n).keys());

If from the very beginning you know the values, then is pretty straightforward:

  const personMap = new Map<string, Person>([
    ['value1', new Person()],
    ['value2', new Person()],
    ['value3', new Person()]
  ]);

If what you want is to create the Map based on some existing generated Array, then you can:

const arrayLength = 5;
const inputArray = Array.from({ length: arrayLength }, (_, index) => [index + '', new Person()]);

const theMap = new Map<string, Person>(
  inputArray.map(x => [x[0], x[1]] as [string, Person])
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM