Easily convert objects to arrays and iterate to your heart’s content.
There are multiple ways of converting an object to an array (which, also is an object but a different one at that.)
Method 1: A simple Object.values() method
The first idea that comes to mind is to just use Object.keys()
, Object.values()
or Object.entries()
to generate an array.
|
|
Method 2: Apply transformation logic during object to array conversion
If you are going fancy about the conversion and want to include some logic therein -
|
|
Method 3: Use slice and call
Remember that call
of one object can be used against another object? We can use this principle to call an array function against the array-like object.
|
|
Method 3.1: Use Array.from()
Array.from() works for array-like iterables including objects. So, we could use them for objects that are arrays in their hearts. This works similar to the previous method in principle and therefore does not deserve a “method” by its own.
|
|
Conclusion
I prefer Object.values()
(or keys
/entries
) to subject an object to array-like operations (yes, I get the subject/object philosophical implications).
Array.prototype.slice()
may be the best performer of the lot.