willmartinsmg
willmartinsmg

Reputation: 5

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

Upvotes: 0

Views: 995

Answers (4)

Bilel BM
Bilel BM

Reputation: 21

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

Upvotes: 1

elad
elad

Reputation: 196

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

Upvotes: -1

Andy
Andy

Reputation: 63524

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

Upvotes: 2

dorriz
dorriz

Reputation: 2679

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

Upvotes: 0

Related Questions