Reputation: 748
I am trying to iterate/map through an array of objects and use nested values, but I cannot seem to get it to work. If i pass in a simple array
const people = [
{ name: "joe", id: "1" },
{ name: "mary", id: "2" }
];
to my ShowList component
const ShowList = (props) => {
const {people} = props;
return ( renderPeep(people))
};
const renderPeep = (people) => (
<ul>
{people.map((peep, index) => (
<li key={index}>{peep}</li>
))}
</ul>
)
I get a list of both values:
joe1
mary1
and both dot notation and bracket dont work ({peep.name}
) to just list names. is the map function causing us to lose keys info on the underlying objects? what am I missing?
Upvotes: 1
Views: 270
Reputation: 22574
Change <li key={index}>{peep}</li>
to <li key={index}>{peep.name}</li>
. Inside the array#map
you are getting an object and you can access name
using dot notation or bracket notation.
Alternatively, you can also use destructuring:
const renderPeep = (people) => (
<ul>
{people.map(({name}, index) => (
<li key={index}>{name}</li>
))}
</ul>
)
const people = [
{ name: "joe", id: "1" },
{ name: "mary", id: "2" }
];
const ShowList = (props) => {
const {people} = props;
return (renderPeep(people));
};
const renderPeep = (people) => (
<ul>
{people.map((peep, index) => (
<li key={index}>{peep.name}</li>
))}
</ul>
)
ReactDOM.render(
<ShowList people={people} />,
document.getElementById('app')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'></div>
Upvotes: 1