1

I have an API which originally returned an array of objects with no key for each object like this:

[
{
"id": 4311,
"title": "C43- Miami Bow Cabinet Handles High Quality Stainless Steel (Polished) Handles",
"liked": false
},
{
"id": 2235,
"title": "C43- Miami Bow Cabinet Handles High Quality Stainless Steel (Brushed) Handles",
"liked": false
}
]

However it would help my app a lot if I could store this data with the id as the key for each nested object, I have updated my API to return data like this:

{
"2235": {
"title": "C43- Miami Bow Cabinet Handles High Quality Stainless Steel (Brushed) Handles",
"liked": false
},
"4311": {
"title": "C43- Miami Bow Cabinet Handles High Quality Stainless Steel (Polished) Handles",
"liked": false
}
}

However now I get an error from react - 'props.posts.map is not a function'

I cant understand what has changed to the data, doesnt redux assign a numerical key to each object if one isnt set anyways?

2
  • 2
    This is not an array anymore. But you can use Object.entries or Object.keys Commented Sep 15, 2017 at 12:38
  • I think you want to give a look at normalizr Commented Sep 15, 2017 at 12:48

2 Answers 2

1

map is meant to work with arrays only as described here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

However, you can use lodash's map method which also works for normalized objects just like yours.

As an example, you can use:

const newArray = _.map(data, (item, key) => {
  // key is the item's id
  return item
})

If using a 3rd party module is not an option, you can work with Object.keys and get the very same result:

const newArray = Object.keys(data).map(key => data[key])
Sign up to request clarification or add additional context in comments.

Comments

1

For store this data with the id as the key for each nested object, you can use reduce:

arr.reduce(function(map, obj){
  map[obj.id] = {
    title: obj.title,
    liked: obj.liked
}
 return map
}, {})

Comments

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.