There are several ways to loop through or enumerate the properties of an object in JavaScript:
- Use a
for...in
loop: Thefor...in
loop iterates over the enumerable properties of an object, and allows you to access the property names and values.
const object = {a: 1, b: 2, c: 3};
for (const property in object) {
console.log(property, object[property]);
}
This will output the following:
a 1
b 2
c 3
- Use
Object.keys()
and afor
loop: TheObject.keys()
function returns an array of the enumerable property names of an object, which you can then iterate over using afor
loop.
const object = {a: 1, b: 2, c: 3};
const keys = Object.keys(object);
for (let i = 0; i < keys.length; i++) {
console.log(keys[i], object[keys[i]]);
}
This will output the same result as the for...in
loop above.
- Use
Object.entries()
and afor...of
loop: TheObject.entries()
function returns an array of arrays, where each inner array consists of a property name and a property value. You can iterate over this array using afor...of
loop.
const object = {a: 1, b: 2, c: 3};
for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}
This will also output the same result as the previous examples.
- Use
Object.getOwnPropertyNames()
and afor
loop: TheObject.getOwnPropertyNames()
function returns an array of all own (non-inherited) properties of an object, including non-enumerable properties. You can iterate over this array using afor
loop.