Underscore: _.keys returning always strings

Created on 6 Feb 2013  ·  5Comments  ·  Source: jashkenas/underscore

_.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!

invalid

Most helpful comment

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);

All 5 comments

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; });
Was this page helpful?
0 / 5 - 0 ratings

Related issues

afranioce picture afranioce  ·  8Comments

arypbatista picture arypbatista  ·  3Comments

haggholm picture haggholm  ·  8Comments

arieljake picture arieljake  ·  4Comments

chikamichi picture chikamichi  ·  8Comments