I have an API returning data in a deeply nested objects within an object within an object format. I am attempting to grab data from some of these deeply nested objects and iterate through them and display them in a React project.
This have been a massive headache and I can't find anything reasonably simple that works.
Lets say I have JSON data that looks like this:
Object {
Object2 {
Object3 {
propertyIWantToAccess1: 'some data',
propertyIWantToAccess2: 'some more data',
propertyIWantToAccess3: 10,
propertyIWantToAccess4: true
}
}
}
How can I, in the render or return function of a component, iterate through these nested objects and grab the properties I want? I think some variation of nested Object.keys.map might be the way to go but I am unsure about how to do this.
Does this need to involve es6 destructuring (a concept that I am not yet comfortable with) or a library like lo-dash?
Edit for clarification: The data is not an array containing objects. It is an object containing many nested objects
I have the data in the API stored in this.state.myPosts
I can console.log the nested object like so:
const data = this.state.myPosts;
const posts = data.content;
console.log(posts);
But when I try to map through the nested object's property using that posts variable I get an error. This doesn't work:
render() {
// Logs data
console.log(this.state.myPosts);
const data = this.state.myPosts;
// Stores nested object I want to access in posts variable
const posts = data.content;
// Successfully logs nested object I want to access
console.log(posts);
// Error, this will not allow me to pass posts variable to Object.keys
const display = Object.keys(posts).map(key =>
<option value={key}>{posts[key]}</option>
)
return(
<div>
{display}
</div>
);
}
I get a TypeError: can't convert undefined to object error. It won't allow me to pass the posts variable to Object.keys. Why?
Object.keysis a good way to iterate over a javascript object properties. Can you show us what you've done so far?