rhavelka
rhavelka

Reputation: 2386

Map Angular Array to Object

I have been looking and have found a few good references for transforming arrays to objects, but I can't seem to find my use case. I have an array with the following format

[
  {id: 1, name: 'hello', display: false},
  {id: 5, name: 'hello2', display: true},
  {id: 7, name: 'hello8', display: true},
]

and I would like to map it into something like this

{
  5: {id: 5, name: 'hello2'},
  7: {id: 7, name: 'hello8'}
}

I have been trying to use the map function, but I can't figure it out since I want the keys of my map to be an id. This is what I have so far but it is obviously wrong.

const myArray = [
  {id: 1, name: 'hello', display: false},
  {id: 5, name: 'hello2', display: true},
  {id: 7, name: 'hello8', display: true},
];

const myMap = myArray.filter(row => row.display)
                     .map(row => {
                         return {row.id: {id: row.id, name: row.name}
                     });

Upvotes: 1

Views: 10130

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

Filter the array, map it to pairs of [id, obj], and convert to an object using Object.fromEntries(). You can use destructuring and rest syntax (...) to remove display.

Notes: if Object.fromEntries() is not supported, change target in TS Config to ES2019.

const arr = [{id: 1, name: 'hello', display: false},{id: 5, name: 'hello2', display: true}, {id: 7, name: 'hello8', display: true}]

const result = Object.fromEntries(
  arr.filter(o => o.display)
    .map(({ display, ...o }) => [o.id, o])
)

console.log(result)

Another option is to use Array.reduce() to create the object. In that case, you can skip objects with false display.

const arr = [{id: 1, name: 'hello', display: false},{id: 5, name: 'hello2', display: true}, {id: 7, name: 'hello8', display: true}]

const result = arr.reduce((acc, { display, ...o }) => {
  if(display) acc[o.id] = [o.id, o]

  return acc
}, {})

console.log(result)

Upvotes: 2

Related Questions