ReactJS map through Object

2019-04-05 10:41发布

I have a response like this:

enter image description here

I want to display the name of each object inside this HTML:

{subjects.map((item, i) => (
  <li className="travelcompany-input" key={i}>
    <span className="input-label">{ item.name }</span>
  </li>
))}   

But it throws an error of subjects.map is not a function.

First, I have to define the keys of the objects where it creates an array of keys, where I want to loop through and show the subject.names.

What I also tried is this:

{Object.keys(subjects).map((item, i) => (
  <li className="travelcompany-input" key={i}>
    <span className="input-label">key: {i} Name: {subjects[i]}</span>
  </li>
))}

4条回答
Summer. ? 凉城
2楼-- · 2019-04-05 11:16

Do you get an error when you try to map through the object keys, or does it throw something else.

Also note when you want to map through the keys you make sure to refer to the object keys correctly. Just like this:

{ Object.keys(subjects).map((item, i) => (
   <li className="travelcompany-input" key={i}>
     <span className="input-label">key: {i} Name: {subjects[item]}</span>
    </li>
))}

You need to use {subjects[item]} instead of {subjects[i]} because it refers to the keys of the object. If you look for subjects[i] you will get undefined.

查看更多
倾城 Initia
3楼-- · 2019-04-05 11:21

You get this error because your variable subjects is an Object not Array, you can use map() only for Array.

In case of mapping object you can do this:

{ 
    Object.keys(subjects).map((item, i) => (
        <li className="travelcompany-input" key={i}>
            <span className="input-label">{ subjects[item].name }</span>
        </li>
    ))
}  
查看更多
男人必须洒脱
4楼-- · 2019-04-05 11:29

Map over the keys of the object using Object.keys():

{Object.keys(yourObject).map(function(key) { return <div>Key: {key}, Value: {yourObject[key]}</div>; })}

查看更多
The star\"
5楼-- · 2019-04-05 11:34

When calling Object.keys it returns a array of the object's keys.

Object.keys({ test: '', test2: ''}) // ['test', 'test2']

When you call Array.map the function takes in 2 arguments; 1. the item, 2. the index.

When you want to get the data, you need to use item instead of i

{Object.keys(subjects).map((keyName, i) => (
    <li className="travelcompany-input" key={i}>
        <span className="input-label">key: {i} Name: {subjects[keyName]}</span>
    </li>
))}
查看更多
登录 后发表回答