首页 > 解决方案 > 从 JSON 数据中循环遍历第一个数组中的多个对象,使用 FUNCTION COMPONENT 在 React 中显示两个带有对象的数组

问题描述

使用FUNCTION COMPONENT在 ReactJS 中访问这些数据的最佳和简单方法是什么?

问题是我有两个带有对象的数组,我想循环通过第一个数组并显示对象内部的每个项目。

控制台日志(数据)

(20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
(20) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

这是数据在每个数组中的表示方式

0:
  first_name: "Jane"
  id: 6
  last_name: "Doe"
  city: "budapest"
1:
  first_name: "Michael"
  id: 10
  last_name: "Holland"
  city: "France"

etc...

(请看下图以了解我所说的“0:”或“1:”的意思。我猜这就是json数据在数组中通过记录显示的方式)

在此处输入图像描述

我下面的当前解决方案仅在您有一个包含对象的数组时才有效,但在这种情况下,您可以看到我有两个。

const items = [
    {first_name: "Jane",id: "6",last_name: "Doe",city: "Budapest"},
    {first_name: "David",id: "10",last_name: "Smith",city: "Paris"},
  ]

  const newData = items.map((item) => {
    return (
      <div className="something" key={item.id}>{item.first_name}</div>
    )
  })

请注意,我使用的是ReactJS 16.9

先感谢您。

标签: javascriptarraysreactjsdata-structuresecmascript-6

解决方案


如果我的理解正确,那么您可以合并两个 Array 然后使用它。

像这样的东西:

// First Array
const stations = [
    {first_name: "Jane",id: "6",last_name: "Doe",city: "Budapest"},
    {first_name: "David",id: "10",last_name: "Smith",city: "Paris"},
];

// Second Array
const stations2 = [
    {first_name: "Jane",id: "6",last_name: "Doe",city: "Budapest"},
    {first_name: "David",id: "10",last_name: "Smith",city: "Paris"},
];

const allStations = [...stations , ...stations2 ]; // <----- HERE

const newData = allStations.map((item) => {
    return (
        <div className="something" key={item.id}>{item.first_name}</div>
    )
})


推荐阅读