Reputation: 7
I'm new to this kinda stuff so bear with me.
I'm receiving an object from Firebase which is structured like this:
{
"news" : {
"BBC news" : {
"id" : 1,
"title" : "BBC News"
},
"CNN News" : {
"id" : 2,
"title" : "CNN News"
},
"title" : "News"
},
"animals" : {
"Horse" : {
"id" : 3,
"title" : "Horse"
},
"title" : "Animals"
}
}
I'm using react and want to loop through this data and render like so:
News
- BBC News
- CNN News
Animals
- Horse
I've have managed to loop through the main titles using this code:
Object.values(this.state.datas).map((data, i) => <li key={i}> {data.title} </li>
The JSON object is assigned to the state 'datas'. Preview of what is rendered at the moment:
News
Animals
I have got the parent titles but not sure how to get the child titles as well.
Does anyone know how I go about getting the result I want? Thank you, sorry If I have used incorrect keywords.
Upvotes: 0
Views: 937
Reputation: 1020
Assuming you can't manipulate your data structure, try doing something like this with your data:
Object.values(this.state.datas).map((data, i) => {
// obtain the categories, i.e. bbc, cnn from the entry
let categories = Object.keys(data);
// pop the "title" key so it doesn't get returned
categories.pop();
return (
<li>
{data.title}
<ul>
{categories.map((category, i) => <li key={i}>{category}</li>)}
</ul>
</li>
);
});
This should work fine without needing to change your data structure from Firebase. Let me know if this works! Check it out at this stackblitz link: https://stackblitz.com/edit/react-szbop7.
Upvotes: 1