Mohiuddin
Mohiuddin

Reputation: 90

can't loop through an object in React?

I am new to React. I am not understanding how to loop through an object. I have a state like this -

const data = {
  name: "doe",
  age: "20",
  mail: "[email protected]",
};
const [user, setUser] = useState(data);

and in JSX I am looping the data like this -

{user.map((userData) => (
    <li>{userData.name}--{userData.age}--{userData.mail}</li>
))}

and the error shows that :

TypeError: user.map is not a function

I want to know how to get a result like this :

[email protected]

Upvotes: 1

Views: 282

Answers (4)

sazzad
sazzad

Reputation: 525

As user is an object you don't need mapping for this. you can directly access object property like this

    <li>{user.name}--{user.age}--{user.mail}</li>
  

Upvotes: 1

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

You can only use map() function on an array and not on an object. If you are willing to loop over the keys of an object, you can do it as follows -

Object.keys(user).map((objectKey) => yourFunction);

But, you don't even need to loop over object keys. If your object is small as it is, you can simply do it as -

<li>
    {user.name}--{user.age}--{user.mail}
</li>

Final Code -

function someComponent() {
    const data = {
        name: 'doe',
        age: '20',
        mail: '[email protected]',
    };

    const [user, setUser] = useState(data);

    return (
        <li>
            {user.name}--{user.age}--{user.mail}
        </li>
    );
}

Alternate Approach -

If you want to make use of looping over keys of your object, you can use Object.keys() to achieve it(this will be preferable if your data has many keys). This can be done in the following way-

const data = {
  name: "doe",
  age: "20",
  mail: "[email protected]",
};

let mystring = ''

Object.keys(data).map((key) => {
  mystring += `${data[key]}--`; // for each key, it will add append the key value and -- to mystring
})
mystring = mystring.slice(0, -2); // to remove the extra -- added at last
console.log(mystring);

Upvotes: 1

pilchard
pilchard

Reputation: 12911

You have assigned user the value of data meaning that it is now an object and you can directly access it key/value pairs.

const data = {
    name: 'doe',
    age: '20',
    mail: '[email protected]',
};

function MyComponent() {

  const [user, setUser] = useState(data);
  
  return (
    <li>{user.name}--{user.age}--{user.mail}</li>
  );
}

Upvotes: 0

Baruch Mashasha
Baruch Mashasha

Reputation: 979

You can't use map function on object.

use Object.keys or convert the object to array of object like this:

const data = [{
  name: "doe",
  age: "20",
  mail: "[email protected]",
}];
const [user, setUser] = useState(data);

Upvotes: 0

Related Questions