Object entries and values add to the rich toolset for managing objects within Javascript.
As I never tire to say - (almost) everything is an object in Javascript. So, how do you access the props / values? It is not as if you are going to count them down - pfft.. are we going to bring down an object to the level of an array?
Also see most of things you should know about object and props
We can directly access the object and props. Or, we iterate over them using for
& friends for objects - all seen before.
|
|
But, if you are feeling that forEach
, for
and friends do not feel as intuitive and there’s something missing - enter entries
.
Object.entries
|
|
Oh.. wait. This is just like for..in
? Yes, in fact except for lesser code and more compact syntax.
|
|
Object.entries
is similar to forEach, and a host of other functions and iterates like one. Except that you can get to the array iterable really quickly using just one statement.
Object.values
Values are very similar to entries, except they provide only values and no props/keys.
|
|
Which should you use?
If you are using Object iterable and really wanted to mix and match with other array variables, I think Object.entries
will be nice. I neither saw significant advantages or limitations of introducing such a variable - but I understand very little in this universe.
We cannot really do a head-to-head comparison between some of the looping routines since they kind of accomplish different goals. You will still loop within Object.entries()
unless you are trying to print out the object.
Also, it should be duly noted that performance does not stand by itself, but is one of the key factors alongside code maintainability.
But, here we are.
|
|
Quick compare on performance -
forEach | for-of | Object.Entries | Object.Values |
---|---|---|---|
2911.062ms 2727.742ms 2764.224ms |
2681.840ms 2681.099ms 2648.367ms |
17.938ms 18.408ms 21.028ms |
17.510ms 12.312ms 11.891ms |
This is not comprehensive performance test - far from it. It is just to give me an idea of how the included routines compare at a superficial level.