简体   繁体   English

React/Javascript - 呈现基于对象数组中相同 Object 键的值列表

[英]React/Javascript - Render a List of Values Based On Same Object Keys Within an Array of Objects

I have an array of objects that looks like this:我有一个看起来像这样的对象数组:

const arr = [
{name: "Bill", email: "bill@email.com"},
{name: "Suzy", email: "suzy@email.com"},
{name: "Jill", email: "Jill@email.com"},
]

I would like to return each value in an <li> .我想返回<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

- bill@email.com
- suzy@email.com
- jill@email.com

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.谢谢。

You should use array.map in JSX, with your code:你应该在 JSX 中使用array.map ,你的代码:

{
  arr.map((item, index) => (
    <li key={index}>{item.email}</li> 
  ))
}

you can do it like this:你可以这样做:

import React, { useState } from 'react';导入反应,{ useState } from 'react';

const Component=()=> {

  const [data, setData] = useState({
    arr = [
      {name: "Bill", email: "bill@email.com"},
      {name: "Suzy", email: "suzy@email.com"},
      {name: "Jill", email: "Jill@email.com"},
    ]
  })

  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>
    </>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM