Reputation: 87
I wanted to display following json data in nested react components .For example a list title with sub list I have tried using for loops but for some reason the component doesn't displays
Choose Your topping 1
let MenuContents = [{
Title:'Choose one',
List:{
Option1:'Regular Base',
Option2:'Stuffed Crust',
Option3: 'Thick Base',
Option4: 'Thin Base'
}
},
{
Title:'Choose one',
List:{
Option1:'Garlic Dip',
Option2:'Chilli Dip',
Option3: 'BBq Dip',
Option4: 'Mayo'
}
},
{
Title:'Choose one',
List:{
Option1:'Tomato Base',
Option2:'BBq Base',
Option3: 'Garlic',
Option4: 'Mayo'
}
}]
MenuContents.map((x) => {
return (
<div>
<div className="AddoneTitle">
<li>
<h3>{x.Title}</h3>
</li>
</div>
<div className='Choose'>
{
Object
.keys(x.List)
.forEach(function(key) {
return( <li>x.List[key]</li>)
})
}
</div>
</div>
)
});
Upvotes: 0
Views: 59
Reputation: 4692
Use
{
x.List.map(record => {
return (
<li key={Object.keys(record)}>
{Object.values(record)}
</li>
)
})
}
instead of:
{
Object.keys(x.List).forEach(function(key) {
return( <li>x.List[key]</li>)
})
}
Upvotes: 1
Reputation: 978
This should work, forEach doesn't return an array of list items as map does, also you were missing {}
inside li
MenuContents.map((x) => {
return (
<div>
<div className="AddoneTitle">
<li>
<h3>{x.Title}</h3>
</li>
</div>
<div className='Choose'>
{
Object
.keys(x.List)
.map(function(key) {
return( <li>{x.List[key]}</li>)
})
}
</div>
</div>);
})
Upvotes: 2