Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

_.keys returning always strings #965

Closed
marcalj opened this issue Feb 6, 2013 · 5 comments
Closed

_.keys returning always strings #965

marcalj opened this issue Feb 6, 2013 · 5 comments
Labels

Comments

@marcalj
Copy link

marcalj commented Feb 6, 2013

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

@caseywebdev
Copy link
Contributor

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

@braddunbar
Copy link
Collaborator

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.

@marcalj
Copy link
Author

marcalj commented Feb 6, 2013

Ouch I see, thanks for the quick response! You rock!!
I was using parseInt(number, 10) but using Number is more clean ;)

Thanks again!

@jhnlsn
Copy link

jhnlsn commented Apr 1, 2013

@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.

@caseywebdev
Copy link
Contributor

@johnymonster with mixed keys, it can be modified to

_.map(_.keys(obj), function (key) { return isNaN(+key) ? key : +key; });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants