ReactJS map through Object
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 you pass will give you 2 arguments;
- the item in the array,
- the index of the item.
When you want to get the data, you need to use item
(or in the example below keyName
) 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>
))}
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>
))
}
Map over the keys of the object using Object.keys()
:
{Object.keys(yourObject).map(function(key) {
return <div>Key: {key}, Value: {yourObject[key]}</div>;
})}