Beginnerprogrammer Beginnerprogrammer - 14 days ago 6
React JSX Question

ReactJS map trough Object

I have an 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 me the error that
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 trough 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>
))}

Answer

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

Object.key({ 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((item, i) => (
    <li className="travelcompany-input" key={i}>
            <span className="input-label">key: {i} Name: {subjects[item]}</span>
    </li>)
)}