Sometimes, we want to map through an object in React.
In this article, we’ll look at how to map through an object in React.
How to map through an object in React?
To map through an object in React, we use some object methods.
For instance, we write
const Comp = () => {
//...
return (
<>
{Object.keys(subjects).map((keyName, i) => (
<li className="travelcompany-input" key={i}>
<span className="input-label">
key: {i} Name: {subjects[keyName]}
</span>
</li>
))}
</>
);
};
to call Object.keys
with the subjects
object to return an array of property keys from subjects
.
Then we call map
with a function that returns a span for each property keyName
.
And we render the property value with subjects[keyName]
.
Conclusion
To map through an object in React, we use some object methods.