How to loop over objects in React
Looping over an object in React:
-
Use
Object.keys()
the method to get an array of object keys. -
Use
map()
the method to iterate over the array of keys.
export default function App() {
const employee = {
id: 1,
name: '迹忆客',
salary: 123,
};
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 use Object.keys
the method to get an array of the object's keys.
const employee = {
id: 1,
name: '迹忆客',
salary: 123,
};
// 👇️ ['id', 'name', 'salary']
console.log(Object.keys(employee));
// 👇️ [1, '迹忆客', 123]
console.log(Object.values(employee));
We can only call the get method on arrays map()
, so we need to get either the array of object keys or the value of the object.
The function we pass to Array.map
the method will be called with each element in the array and the index of the current iteration.
We used an index on the key in our examples
prop
, but if you have a stable, unique identifier, it's better to use that.
When iterating over an object's keys, it is safe to use the object's key for the key prop, since keys within an object are guaranteed to be unique.
export default function App() {
const employee = {
id: 1,
name: '迹忆客',
salary: 123,
};
return (
<div>
{/* 👇️ iterate object KEYS */}
{Object.keys(employee).map(key => {
return (
<div key={key}>
<h2>
{key}: {employee[key]}
</h2>
<hr />
</div>
);
})}
</div>
);
}
However, if we are iterating over the values of an object, we cannot safely use the value of the key property unless we can be sure that all values in the object are unique.
React uses the key prop internally for performance reasons. It helps the library ensure that only array elements that have changed are re-rendered.
Having said that, unless we are dealing with thousands of array elements, we won't see any noticeable difference between using indices and stable unique identifiers.
Looping over object values in React:
-
Use
Object.values()
the method to get an array of object values. -
Use
map()
the method to iterate over an array of values.
export default function App() {
const employee = {
id: 1,
name: '迹忆客',
salary: 123,
};
return (
<div>
{/* 👇️ iterate object VALUES */}
{Object.values(employee).map((value, index) => {
return (
<div key={index}>
<h2>{value}</h2>
<hr />
</div>
);
})}
</div>
);
}
We use Object.values
the method to get an array of object values.
const employee = {
id: 1,
name: '迹忆客',
salary: 123,
};
// 👇️ [1, '迹忆客', 123]
console.log(Object.values(employee));
If we only want to render the values of the object, we can access them directly using this method.
We can also use Object.entries
the method, which returns an array of arrays of key-value pairs.
export default function App() {
const employee = {
id: 1,
name: '迹忆客',
salary: 123,
};
console.log(Object.entries(employee));
return (
<div>
{Object.entries(employee).map(([key, value]) => {
return (
<div key={key}>
<h2>
{key}: {employee[key]}
</h2>
<hr />
</div>
);
})}
</div>
);
}
Here is Object.entries()
what the output of the method looks like.
const employee = {
id: 1,
name: '迹忆客',
salary: 123,
};
// 👇️ [
// ['id', 1],
// ['name', '迹忆客'],
// ['salary', 123],
// ]
const result = Object.entries(employee);
console.log(result);
This method returns an array containing a sub-array of key-value pairs.
Another approach is to use Array.forEach()
the method to iterate over the keys of the object and push the JSX elements into an array, which we will then render.
export default function App() {
const employee = {
id: 1,
name: '迹忆客',
salary: 123,
};
const results = [];
Object.keys(employee).forEach(key => {
results.push(
<h2 key={key}>
{key}: {employee[key]}
</h2>,
);
});
return (
<div>
{results}
</div>
);
}
The method is called for each key Array.forEach()
, but forEach()
the method returns undefined , so we can't use it directly in JSX code.
Instead, we push the JSX element into the array we render.
注意
, which is a more indirect approach that we won't see used often in React applications.
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
React Tutorial - Transferring Props
Publish Date:2025/03/16 Views:185 Category:React
-
React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.
React Tutorial: Props Anti-Pattern
Publish Date:2025/03/16 Views:183 Category:React
-
React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.
React Tutorial - Props Validation
Publish Date:2025/03/16 Views:99 Category:React
-
Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.
React tutorial: Types of Props for child components
Publish Date:2025/03/16 Views:170 Category:React
-
Usually, the child components of a React component are a group, that is, the child components are an array. Introduction to Type of the Children Props.
How to solve the error Uncaught TypeError: Cannot read properties of undefined in
Publish Date:2025/03/16 Views:150 Category:React
-
In the process of React development, we often encounter some errors. Here we look at an error reported in App.js. The error is as follows: App.js:69 Uncaught TypeError: Cannot read properties of undefined (reading 'setState') at onInput
Why do you need to bind event handlers in React Class Components?
Publish Date:2025/03/16 Views:58 Category:React
-
When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:
Solution to the error "does not contain a default export" in React
Publish Date:2025/03/16 Views:187 Category:React
-
When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.
Error in React: Attempted import error 'X' is not exported from Solution
Publish Date:2025/03/16 Views:76 Category:React
-
In React, the error “Attempted import error 'X' is not exported from” in React.js occurs when we try to import a named import that does not exist in the specified file. To fix the error, make sure the module has named exports and you have not obfu
Solve the Module not found: Can't resolve 'react-bootstrap' error
Publish Date:2025/03/16 Views:85 Category:React
-
To resolve the error "Module not found: Error: Can't resolve 'react-bootstrap'", make sure to install the react-bootstrap package by opening a terminal in the root directory of the project and running the command `npm install react-bootstrap bootstrap