I've got a sparse array that I want to represent in JSON. For example:
-10 => 100
-1 => 102
3 => 44
12 => -87
12345 => 0
How can I do this? Can I do this?
I've got a sparse array that I want to represent in JSON. For example:
-10 => 100
-1 => 102
3 => 44
12 => -87
12345 => 0
How can I do this? Can I do this?
You can represent it as a simple object:
Since it will be a simple object, you cannot iterate it the same way as an array, but you can use the
for...in
statement:And if you want to access an specific element by key, you can use also here the square bracket property accessor:
Note that I use the
hasOwnProperty
method inside thefor...in
loop, this is to prevent iterating properties defined on higher levels of the prototype chain, which can cause problems and unexpected behavior... more info here.