Borislav Hadzhiev
Last updated: Apr 22, 2022
Photo from Unsplash
Use the Object.keys()
method to map through an object in React, e.g.
Object.keys(employee).map()
. The Object.keys
method returns an array of the
object's keys on which we can call the map()
method.
export default function App() { const employee = { id: 1, name: 'Alice', salary: 100, }; return ( <div> {/* 👇️ iterate object KEYS */} {Object.keys(employee).map((key, index) => { return ( <div key={index}> <h2> {key}: {employee[key]} </h2> <hr /> </div> ); })} <br /> <br /> <br /> {/* 👇️ iterate object VALUES */} {Object.values(employee).map((value, index) => { return ( <div key={index}> <h2>{value}</h2> <hr /> </div> ); })} </div> ); }
We used the Object.keys method to get an array of the object's keys.
const employee = { id: 1, name: 'Alice', salary: 100, }; // 👇️ ['id', 'name', 'salary'] console.log(Object.keys(employee)); // 👇️ [1, 'Alice', 100] console.log(Object.values(employee));
We can only call the map() method on arrays, so we need to either get an array of the object's keys, or the object's values.
The function we passed to the Array.map method gets called with each element in the array and the index of the current iteration.
index
for the key
prop in the examples, however it's better to use a stable, unique identifier if you have one.When iterating over an object's keys, it's safe to use the object's key for the
key
prop, because the keys in an object are guaranteed to be unique.
export default function App() { const employee = { id: 1, name: 'Alice', salary: 100, }; return ( <div> {/* 👇️ iterate object KEYS */} {Object.keys(employee).map(key => { return ( <div key={key}> <h2> {key}: {employee[key]} </h2> <hr /> </div> ); })} </div> ); }
However, if you're iterating over the object's values, you can't safely use the
value
for the key
prop, unless you can be certain that all of the values in
the object are unique.
The key
prop is used internally by React for performance reasons. It helps the
library make sure to only re-render the array elements that have changed.
index
and a stable, unique identifier unless you're dealing with many thousands of array elements.To map through an object's value in React:
Object.values()
method to get an array of the object's values.map()
method on the array of values.export default function App() { const employee = { id: 1, name: 'Alice', salary: 100, }; return ( <div> {/* 👇️ iterate object VALUES */} {Object.values(employee).map((value, index) => { return ( <div key={index}> <h2>{value}</h2> <hr /> </div> ); })} </div> ); }
We used the Object.values method ot get an array of the object's values.
const employee = { id: 1, name: 'Alice', salary: 100, }; // 👇️ [1, 'Alice', 100] console.log(Object.values(employee));
If you only want to render the object's values, you can directly access them using this approach.