1

I have an array of objects that looks like this:

const arr = [
{name: "Bill", email: "[email protected]"},
{name: "Suzy", email: "[email protected]"},
{name: "Jill", email: "[email protected]"},
]

I would like to return each value in an <li>. One list for names, one list for emails. Like this:

return (
  <>
    <div className="names">
      <ul>
        {arr.forEach((item) => {
          return <li>item.name</li>;
        })}
      </ul>
    </div>

    <div className="emails">
      <ul>
        {arr.forEach((item) => {
          return <li>item.email</li>;
        })}
      </ul>
    </div>
  </>
);

so that it looks like this:

- Bill
- Suzy 
- Jill

- [email protected]
- [email protected]
- [email protected]

But, of course what I am doing does not look like this, which is why I am asking this question. What can I do with my array of objects to generate the desired list layout? Thanks.

2

2 Answers 2

1

You should use array.map in JSX, with your code:

{
  arr.map((item, index) => (
    <li key={index}>{item.email}</li> 
  ))
}
Sign up to request clarification or add additional context in comments.

Comments

1

you can do it like this:

import React, { useState } from 'react';

const Component=()=> {

  const [data, setData] = useState({
    arr = [
      {name: "Bill", email: "[email protected]"},
      {name: "Suzy", email: "[email protected]"},
      {name: "Jill", email: "[email protected]"},
    ]
  })

  return (
    <>
      <div className="names">
        <ul>
          //this map will render all the names inside arr array one by one inside an li
          {data.arr.map((item, index) => (
            <li key={index}>{item.name}</li> 
          ))
          }
        </ul>
      </div>

      <div className="emails">
        //this map will render all the emails inside arr array one by one inside an li
        {data.arr.map((item, index) => (
          <li key={index}>{item.email}</li> 
        ))  
        }
      </div>
    </>
  );
}

Comments

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.