This is done in the node shell:
> results = []
[]
> num = 5
5
> results[num] = []
[]
> results
[ , , , , , [] ]
>
And even if I try to stringify the number:
> results = []
[]
> num = 5
5
> results[num.toString()] = []
[]
> results
[ , , , , , [] ]
> results['5'] = []
[]
> results
[ , , , , , [] ]
>
It would seem that javascript is interpreting a string as a number in the definition of an object?
I’d like the results to look like this:
results = [ { '5' : [
{ key : value },
{ key2 : value }
]
}
]
You’re not working with just any kind of object.
[]is an Array, and has certain magical properties — one of them being that non-negative integer-looking keys extend the array. Even if they’re strings, that doesn’t matter — all object keys are strings anyway, and arrays are still objects.Try using
{}rather than[]if you don’t want arrays’ special treatment of integer-looking keys.Course, if you’re looking to make the value a bunch of key/value pairs as well, you might consider saying
results[5] = {}.The
[]s you’re asking for seem kinda broken in most cases. Javascript objects are by their very nature dictionaries, and having a list of them with one key/value pair each seems to add complexity without real gain. The exception would be if you want to have a bunch of values per key and are willing to put up with the added ugliness of having to loop through the whole list of pairs each time you want to find something.