JavaScript forEach() function lets you iterate over an array, but not over an object. If you want to iterate over a JavaScript object using forEach() then first convert an object into an array, using Object.keys(), Object.values(), or Object.entries().
Under ECMAScript 5, you can combine Object.keys()
and Array.prototype.forEach()
:
var obj = {
first: "John",
last: "Doe"
};
Object.keys(obj).forEach(function(key) {
console.log(key, obj[key]);
});
Example forEach object JavaScript
Simple example code iterates over each key in the object using forEach() with Object.keys()
function.
<!DOCTYPE html>
<html>
<body>
<script>
const obj = {
name: 'James Bond',
rank: '007'
};
Object.keys(obj).forEach(key => {
console.log(key, obj[key]);
});
</script>
</body>
</html>
Output:
Using Object.values()
Object.values(obj).forEach(val => {
console.log(val);
});
Using Object.entries()
Object.entries(obj).forEach(entry => {
const [key, value] = entry;
console.log(key, value);
});
Do comment if you have any doubts or suggestions on this JS object topic,
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version