1

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

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

4 Comments

I am getting an error about fromEntries() not being a function, but I am currently on es2017. I am upgrading to es2019 and will get back if it works
If not, use the 2nd solution, which doesn't require changes to the target.
thank you. I feel like there should be an easier way to convert an array into an object but your solution works for me
Not in native js. In lodash, for example, you have _.keyBy(arr, 'id'), but it won't filter or remove display.

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.