Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map list of objects to dictionary or map?

Tags:

typescript

I am trying to create a childDict for later usage. I'm not just trying actually, I am succeeding.

This works:

const childDict = new Map(
  this.voteCards.toArray().map(card => {
    return [card.placeInfo.id, card.placeInfo];
  })
);

However, the interpreter is not happy. I'll spare you the error message which is just a type conflict.

enter image description here

So how can I map a list to a dictionary or map?

like image 474
Stefan Falk Avatar asked Sep 15 '25 10:09

Stefan Falk


1 Answers

Here is a way to convert array of Objects to a dictionary in one line:

var voteCardsArray = [
    { placeInfo: { id: 42, desc: 'stuff 42' } },
    { placeInfo: { id: 65, desc: 'stuff 65' } },
    { placeInfo: { id: 89, desc: 'stuff 89' } },
];

var res = Object.assign({}, ...voteCardsArray.map(card => ({[card.placeInfo.id]: card.placeInfo})));

console.log(res)
like image 185
mehdi Ichkarrane Avatar answered Sep 18 '25 11:09

mehdi Ichkarrane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!