0

How to loop through or enumerate a JavaScript object?

In Vanilla-JS

var obj = {
    "attr1": "value1",
    "attr2": "value2",
    "attr3": "value3"
};

for (var key in obj) {
    if (obj.hasOwnProperty(key)) {
        console.log(key + " -> " + obj[key]);
    }
}
RUN

ECMAScript 5

const obj = {
    "attr1": "value1",
    "attr2": "value2",
    "attr3": "value3"
};

Object.keys(obj).forEach(function(key) {
    console.log(key + " -> " + obj[key]);
});
RUN

ECMAScript 6

const obj = {
    "attr1": "value1",
    "attr2": "value2",
    "attr3": "value3"
};

for (const key of Object.keys(obj)) {
    console.log(key + " -> " + obj[key]);
}
RUN

ECMAScript 8

const obj = {
    "attr1": "value1",
    "attr2": "value2",
    "attr3": "value3"
};

Object.entries(obj).forEach(
    ([key, value]) => console.log(key + " -> " + value)
);
RUN
add comment
Suggest a different solution or add another example