_.keys({111: 222, 333: 444})
returns ["111", "333"]
, but expected [111, 333]
.
Also affects other functions like _.pairs: _.pairs({1: 1})`returns`[["1", 1]]`, but expected`[[1, 1]]
.
Thanks!
Keys are always strings.
var obj = {};
obj[1] = 1;
for (var key in obj) console.log(typeof key); // string
You can look up key '1'
with obj[1]
or obj['1']
as a convenience, not because the key is a number.
If you want the keys as numbers, try
var obj = {};
obj[1] = 1;
_.map(_.keys(obj), Number);
Hi @marcalj! Returning property names as strings is part of the spec. If you need numbers, @caseywebdev's solution above will work for most cases.
Ouch I see, thanks for the quick response! You rock!!
I was using parseInt(number, 10)
but using Number
is more clean ;)
Thanks again!
@caseywebdev solution wont work when you have mixed key objects. such as {"asdf":123, 1:1234} I do realize you said "most" cases, i was just pointing out when it wouldn't work.
@johnymonster with mixed keys, it can be modified to
_.map(_.keys(obj), function (key) { return isNaN(+key) ? key : +key; });
Most helpful comment
Keys are always strings.
You can look up key
'1'
withobj[1]
orobj['1']
as a convenience, not because the key is a number.If you want the keys as numbers, try