1

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?

3
  • 1
    nope. you should be able to do peep.name or peep.id. Commented Dec 24, 2017 at 6:33
  • 1
    yep. I just realized I succumbed to the combinatorial problem of Javascript- every library addition completely changes everything, i.e. deciding between 5 libraries means theres 32 different implementations I need to learn. In my case, I wasn't actually passing in the people object, i was passing it to Immutable js fromJS function. So, it was peep.get('name') that I needed. Commented Dec 24, 2017 at 7:06
  • make sense if you are using immutable.js Commented Dec 24, 2017 at 7:10

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Actually this is the exact problem the OP mentioned, that peep.name is not working as expected: "and both dot notation and bracket dont work ({peep.name} )..."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.