How to use Object.values() method and forEach() Method In Javascript
The Object.values() method returns an array of the object’s own enumerable property values. By combining this with the forEach() method, you can iterate over each value. To also access the corresponding keys, you can use the Object.keys() method in tandem.
Syntax:
Object.values(exampleObj).forEach((value, index) => {
const key = Object.keys(exampleObj)[index];
console.log(key, value);
});
Example:
function iterateObject() {
let exampleObj = {
book: "Sherlock Holmes",
author: "Arthur Conan Doyle",
genre: "Mystery"
};
Object.values(exampleObj).forEach((value, index) => {
const key = Object.keys(exampleObj)[index];
console.log(key, value);
});
}
iterateObject();
Output
book Sherlock Holmes author Arthur Conan Doyle genre Mystery
How to iterate over a JavaScript object ?
In this article, we will learn how to iterate over a JavaScript object. During iteration, you loop through the object’s properties one by one, and depending on the method you use for iteration, you might have different access to these properties
There are many methods to iterate over an object which are discussed below:
Table of Content
- Using for…in loop
- Using Object.entries() method and map() Method
- Using forEach() method and object.keys() Method
- Using Lodash _.forOwn() Method