Reputation: 4826
I have a data structure as below:
{
oldPics: {
[title: 'dog', url: 'www.dog.com'],
[title: 'cat', url: 'www.cat.com'],
[title: 'bird', url: 'www.bird.com'],
},
newPics: {
[title: 'fox', url: 'www.fox.com'],
[title: 'lion', url: 'www.lion.com'],
},
archivedPics: {
[title: 'eagle', url: 'www.eagle.com'],
[title: 'fish', url: 'www.fish.com'],
[title: 'monkey', url: 'www.monkey.com'],
},
}
I want to display the data like this:
<div>
<div>
<h3>old</h3>
<p>title: dog, url: www.dog.com</p>
<p>title: cat, url: www.cat.com</p>
<p>title: bird, url: www.bird.com</p>
</div>
<div>
<h3>new</h3>
<p>title: fox, url: www.fox.com</p>
<p>title: lion, url: www.lion.com</p>
</div>
<div>
<h3>archived</h3>
<p>title: eagle, url: www.eagle.com</p>
<p>title: fish, url: www.fish.com</p>
<p>title: monkey, url: www.monkey.com</p>
</div>
</div>
I have tried in my component to render it as below but it renders empty <div>
elements:
_renderPics(group) {
const content = []
const piccies = Object
.keys(group)
.map(key => content.push(
<div key={key}>title: {group[key].title} url: {group[key].url}</div>
));
return content
}
Any idea?
Upvotes: 1
Views: 1145
Reputation: 169
You must correct your data structure from
oldPics: {
[title: 'dog', url: 'www.dog.com'],
[title: 'cat', url: 'www.cat.com'],
[title: 'bird', url: 'www.bird.com'],
}
To
oldPics: [
{title: 'dog', url: 'www.dog.com'},
{title: 'cat', url: 'www.cat.com'},
{title: 'bird', url: 'www.bird.com'},
]
then
{Object.keys(group).map((key, y) =>
<div key={y}>
<h3>{key.replace('Pics', '')}</h3>
{group[key].map((item, y) =>
<div key={y}>title: {item.title} url: {item.url}</div>
)}
</div>
)}
https://codesandbox.io/s/1r3mp5jnj4
Upvotes: 1
Reputation: 193291
Assuming that your data structure is correct in your real case, two nested maps should do the job:
_renderPics(group) {
return Object
.keys(group)
.map((key, index) => (
<div key={index}>
<h3>{key.replace('Pics', '')}</h3>
{group[key].map((pic, i) => (
<div key={i}>title: {pic.title}, url: {pic.url}</div>
))}
</div>
));
}
Demo: https://codesandbox.io/s/l94mml0yj9
Upvotes: 2