简体   繁体   中英

Display array value with multiple objects

I need to display the values in my UsersData array, same as array numbers, but I can not do that in ReactJS.

Here's an example available in CodeSandbox.

https://codesandbox.io/s/n08n2m7mpj

import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const usersData = [
    {
      total: 3,
      data: [
        { id: 1, name: "Tania", username: "floppydiskette" },
        { id: 2, name: "Craig", username: "siliconeidolon" },
        { id: 3, name: "Ben", username: "benisphere" }
      ]
    }
  ];

  const numbers = [1, 2, 3, 4, 5];

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      {numbers.map((number, index) => (
        <li key={index}>{number}</li>
      ))}

      {usersData.length > 0 ? (
        usersData.map((data, index) => <div key={index}>Nome: {data.name}</div>)
      ) : (
        <div>No users </div>
      )}
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

1) usersData is an array containing one element (an object)

2) You need to iterate over the data array of that object and display the value of name property for each its objects.

{usersData[0].data.length > 0 ? (
  usersData[0].data.map((obj, index) => <div key={index}>Nome: {obj.name}</div>)
) : (
  <div>No users </div>
)}

Forked update

Your usersData is an array usersData=[] which contains an object usersData=[{}] which itself contains the array of data usersData=[{data: []}] so you need to change your variable to an object and use the map function on the array of data inside it like so

    const usersData = {
      total: 3,
      data: [
        { id: 1, name: "Tania", username: "floppydiskette" },
        { id: 2, name: "Craig", username: "siliconeidolon" },
        { id: 3, name: "Ben", username: "benisphere" }
      ]
    };

and your loop would become

      {usersData.data.length > 0 ? (
        usersData.data.map((user, index) => <div key={index}>Nome: {user.name}</div>)
      ) : (
        <div>No users </div>
      )}

You need to do

  usersData[0].data.map(({name}, index) => <div key={index}>Nome: {name}</div>)

Becaise you are not accessing the data array in your code above

usersData.map((userData, index) => {
     return userData.data.map(item => {
         return <div key={index + item.id}>Nome: {item.name}</div>;
     });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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