In ES6/2015 you can loop through an object like this: (using arrow function)
Object.keys(myObj).forEach(key => {
console.log(key); // the name of the current key.
console.log(myObj[key]); // the value of the current key.
});
In ES7/2016 you can use Object.entries
instead of Object.keys
and loop through an object like this:
Object.entries(myObj).forEach(([key, val]) => {
console.log(key); // the name of the current key.
console.log(val); // the value of the current key.
});
The above would also work as a one-liner:
Object.entries(myObj).forEach(([key, val]) => console.log(key, val));
In case you want to loop through nested objects as well, you can use a recursive function (ES6):
const loopNestedObj = obj => {
Object.keys(obj).forEach(key => {
if (obj[key] && typeof obj[key] === "object") loopNestedObj(obj[key]); // recurse.
else console.log(key, obj[key]); // or do something with key and val.
});
};
Same as function above, but with ES7 Object.entries()
instead of Object.keys()
:
const loopNestedObj = obj => {
Object.entries(obj).forEach(([key, val]) => {
if (val && typeof val === "object") loopNestedObj(val); // recurse.
else console.log(key, val); // or do something with key and val.
});
};
Here we loop through nested objects change values and return a new object in one go using Object.entries()
combined with Object.fromEntries()
(ES10/2019):
const loopNestedObj = obj =>
Object.fromEntries(
Object.entries(obj).map(([key, val]) => {
if (val && typeof val === "object") [key, loopNestedObj(val)]; // recurse
else [key, updateMyVal(val)]; // or do something with key and val.
})
);
Another way of looping through objects is by using for ... in and for ... of. See @vdegenne's nicely written answer.