The Basics/Utility Classes/ObjectIterator
¶
Reference Documentation
Find reference documentation for ObjectIterator
here, or
navigate to it via the 'Reference' tab.
How many times have you typed out the classic for (let prop of Object.keys(myObj)) ...
mantra? More than three times?
Yeah, me too. Here's an easy way to loop over the key-value pairs present in an object:
1 2 3 4 5 6 7 |
|
The Simple Stuff¶
If you hadn't figured it out from that example, ObjectIterator
instances provide the ability to iterate over the
key-value pairs of a provided input object, returning KeyValuePair
s.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
Type Support¶
As we alluded to in the first example on this page, if you have more strictly-typed objects you can also pass a type to ObjectIterator.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
A Word of Warning¶
One small hiccup - in JavaScript, every object (every object) stores its keys as strings. This means that, when attempting to use an object that has (read: appears to have) numeric keys, the keys will be 'coerced' into strings.
I put air quotes around 'coerced' because there isn't actually any type coercion occurring - the keys were always strings.
The only time actual number-to-string coercion occurs is when an array is passed to the ObjectIterator
constructor. In
this situation, the indices of the elements of the provided array will be returned as strings:
1 2 3 4 5 6 7 8 9 10 11 |
|