0

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?

1
  • I have edited my answer Commented Jun 6, 2020 at 13:57

2 Answers 2

1

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());
Sign up to request clarification or add additional context in comments.

3 Comments

size seems to be a number, not an array.
In the first example OP provided a working code, which is based on loop. Seems from there size is an array. OP needs to clarify more.
@NavoneelTalukdar Just to understand what you are suggesting is to use map over Array.from() overload that takes a mapping function to make it more readable. Yes this is much better. But I was trying to arrive at a way which doesnt include creating additional Array to loop over. Now to get the desired map I will still have to pass the result to a Map constructor. var result = sizeArr.map((i): [string, Person] => [i, {} as Person]); const resultToBeReturned = new Map<string, Person>(result);
0

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])
);

2 Comments

OP's code shows that the size can be anything and should be dynamic.
Thanks @JoseGuzman, looks like with your solution, we end up using both Array.from overload that takes a mapping function along with another call to map in the Map constructor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.