Iterate through nested Object/Arrays in React

Can anyone explain to me how to iterate through deeply nested objects and arrays in React? I’ve had this issue for MONTHS and I still can’t figure out a solution that works.

Is it common to just say the hell with it and use a query language/package for this?

This is hands down the most difficult thing I’ve encountered in web dev/computer science. There seems to be no method to the madness.

Yeah this is a problem that trips me up often.

The easiest thing to do is to design your state/store to be as shallow as possible.

Apart from that you and up doing lots of copying of whole nested objects, and relying on the spread/rest operators to overwrite the necessary parts.

Edit

Oh, I just re-read this. You are talking about iterating rather than updating deeply nested state. My apologies!

Could you give an example of what you are trying to do?

I mean accessing deeply nested JSON data that is any arbitrary combination of arrays/objects nested within one another and any number of levels deep.

This has me pulling my hair out every time I work with an API. It’s always some convoluted nightmare of using nested Object.keys.map and .map within one another with multiple return statements and it’s just a huge headache.

I have Redux giving me the following JSON data from an API. The payload contains an array with 20 items called items. Each array element in that items array has (0-19) has a name property. How can I access the names of each object nested within this items array?

I’ve been fighting with this for 2 days and can’t get it working. I’ve tried to implement every combination of Object.keys.map/.map imaginable and still can’t access the names property.

const otherAlbums = Object.keys(this.props.otherAlbums.albums).map(item => {
      return item;
    });

The above code access the array elements, in this case, 0-19. If I console.log otherAlbums it prints out 0,1,2,3,…19.

Why can’t I go one level deeper into an individual element and grab the name property.

For example return item[0].name does not work. Why? I’m not understanding why I can’t use dot notation to access the properties of each other these nested objects.

Have you tried fetching payload.items from the api as the response instead of just payload.
i.e
fetch(api).then(payload => payload.items).
From there you can map payload.items