Reputation: 6675
If I have this object:
const json = {
products: [
{
id: 0,
name: "Chair Roby",
style: "Leather",
color: "red",
}
]
};
I can map over the array inside of it and show all the items in the object inside the array like this:
const prod = json.products.map(item => {
return (
<ul>
<li>
{item.name}
</li>
<li>
{item.style}
</li>
<li>
{item.color}
</li>
</ul>
);
});
This listed me the values, but how could I show also the keys such as name, style and color?
Upvotes: 0
Views: 45
Reputation: 1636
const prod = json.products.map(item =>
<ul>
{Object.entries(item).map((key, value) =>
<li>{key}: {value}</li>
}
</ul>
);
Upvotes: 1
Reputation: 410
The best aproach is this:
const prod = Object.keys(json.products).forEach(productKey => {
return ( <ul> <li> {productKey} - {json.products[productKey]} </li> </ul> );
});
Upvotes: 2
Reputation: 370679
Use another nested map over the Object.entries
of each item:
const json = {
products: [
{
id: 0,
name: "Chair Roby",
style: "Leather",
color: "red",
},
{
foo: 'bar'
}
]
};
class MyList extends React.Component {
render() {
return json.products.map((obj) => (
<ul>
{
Object.entries(obj).map(([key, val]) => (
<li>
{('key: ' + key + ', val: ' + val)}
</li>
))
}
</ul>
));
}
}
ReactDOM.render(
<MyList />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>
Upvotes: 2