JavaScript: 5 Ways to loop the JS Object
There are multiple ways to loop through object in JavaScript with little but important difference that might bug you in some case.
Let’s see all of the popular ways.
For-based solution
solution 1: for-in
for(var key in obj) {
console.log(key,obj[key])
}
solution 2: for-of + Object.keys
for(var key of Object.keys(obj)) {
console.log(key, obj[key])
}
and some browser support
solution 3: for-of + Object.entries
for (let [key, value] of Object.entries(p)) {
console.log(`${key}: ${value}`);
}
Call back style solution
solution 4: Object.keys.forEach Callback
Object.keys(obj).forEach((key) => {
console.log(key, obj[key])
})
and Object.entries
solution 5: Object.entries Callback
Object.entries(obj).forEach([key,val] => {
console.log(key, val)
}
Differences
for vs callback
We prefer callback style when we want to do some functional programming after the object. For example:
var finalValue = Object.entries(obj).filter(f1).map(f2).reduce(f3)
Otherwise the for
solution provide more readability.
Object.keys vs Object.entries
This is easy if you want key, val
directly without getting value of such key by calling obj[key]
use Object.entries
Differences on Inheritance
Then we see how solution 1 vs 2 this is more complicated
var obj1 = {a:1,b:2}
var obj2 = Object.create(obj1)
obj2.c = 3for(var key in obj2) {
console.log(key)
}
// print a,b,cfor(var key of Object.keys(obj2)){
console.log(key)
}
// print only c
If you want everything including inherited property use for-in
. If you want only property that you assign directly to that object not more than that use for-of
.
You can make for-in
work like for-of
with hasOwnProperty
filter but I think why not we just use for-of
.
Bonus on object creation
There is an unpopular way to create an object in JavaScript with new
keyword. Java developer familiar with this but it’s a bad practice in JavaScript.
I discuss this new
keyword because it might make above discussion and example work differently.
You can try this in Chrome or Node console.
var obj = {a:1,b:2}
var obj1 = new Object(obj)
var obj2 = Object.create(obj)obj1
> {a:1, b:2}obj2
> {}
__proto__ : {a:1,b:2}This is weird. Empty object!?obj2.a
> 1
obj2.b
> 2No, it's not.
This can be weird. The obj2
have nothing inside. The inherited property from parent is inside the __proto__
link just like the directory have above directory but it’s callable from obj2.a
and obj2.b
.
This is flexible inheritance with __proto__
which is fast and good. Never try to make JavaScript looks like Java and vice versa.
Cheers
Web Application | Software | IoT
www.codemonday.com