Iterate over “Object” in Javascript, for loop? 🫣

Lalitwadee Damyos
2 min readNov 7, 2022

--

Photo by Zachariah Aussi on Unsplash

Do you wonder how we loop through Object { key: value }in Javascript or just forgot it like myself? Here is your quick note!

Level 1 - Simple For Loop (can skip it)

We can use a simple for loop in Javascript to do this as we loop through each property from Object.keys() for instance;

const object = { a: 1, b: 2, c: 3 };
const properties = Object.keys(object)
for (i = 0; i < properties.length; i++) {
const property = properties[i];
console.log(`${property}: ${object[property]}`);
}
// expected output:
// "a: 1"
// "b: 2"
// "c: 3"

Ready for level 2?

Ready?

Level 2 - Use for...in

Javascript has for...in ready for you to loop through Object as we have property or key in each iteration and we can access each value by calling object[property] for instance;

const object = { a: 1, b: 2, c: 3 };for (const property in object) {
console.log(`${property}: ${object[property]}`);
}
// expected output:
// "a: 1"
// "b: 2"
// "c: 3"

Bonus ⭐️ Check if the property exists

If we want to check if it has its own property in the current object (not the inherited one) we can use Object.hasOwn()

const triangle = { a: 1, b: 2, c: 3 };

function ColoredTriangle() {
this.color = "red";
}

ColoredTriangle.prototype = triangle;

const obj = new ColoredTriangle();

for (const prop in obj) {
if (Object.hasOwn(obj, prop)) {
console.log(`obj.${prop} = ${obj[prop]}`);
}
}

// Logs:
// "obj.color = red"

It logs only the [color] value because it’s the only property that is owned by ColoredTriangle , property [a, b, c] are the inherited ones (by using .prototype

😘 Explanation of Object inheritance in Javascript will be in the next blog.

Note: Object.hasOwn() is intended as a replacement for Object.prototype.hasOwnProperty().

It is recommended over Object.prototype.hasOwnProperty() because it works for objects created using Object.create(null) and with objects that have overridden the inherited hasOwnProperty() method. While it is possible to workaround these problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn() is more intuitive.

Ref: Object.hasOwn()

--

--

Lalitwadee Damyos
Lalitwadee Damyos

Written by Lalitwadee Damyos

Senior Full Stack Software Engineer 🌈

No responses yet