0

Let's say I've got array of objects:

let items = [
    { id: 1, name: 'one'},
    { id: 2, name: 'two'},
    { id: 3, name: 'three'},
];

Then I've got result object as index signature type:

let result: {[key: number]: string};

How can I map items to result using Array.prototype.map function?

I can't get the correct syntax for something like this:

result = array.map(elem => {[key: elem.id]: elem.name});
Daniel Gadawski
  • 1,893
  • 4
  • 20
  • 32
  • 1
    `Array.map()` is more suited to modifying the content of an array. You instead want to create/populate another object. Try combining `Object.entries()` and `Array.reduce()`. – fubar Jul 12 '23 at 08:28
  • 1
    You could use `Array.forEach()` and assign the properties of `result` in each iteration like [this](https://tsplay.dev/wQJjYN) – Cuzy Jul 12 '23 at 08:34
  • You forgot to return in your map function. – Wimanicesir Jul 12 '23 at 08:47
  • @fubar `Array.map()` isn't for modifying the content of an array. It's for creating a new array (with the same number of elements). – RoToRa Jul 12 '23 at 12:57
  • @RoToRa agreed. Poor choice of words on my part. It does create a new array, but it does so by mapping and modifying the content of the original array. – fubar Jul 12 '23 at 18:27

0 Answers0