ajorgensen
ajorgensen

Reputation: 5151

Getting keys from associative array in javascript

In javascript (or CoffeScript) is there a way to just get the keys for a associative array? The real problem I am trying to solve is to create a set but the only way I found that is to create a map and use the keys to produce the set. I know I can iterate over the elements and collect them but that seems like extra work to me.

So for example in CoffeeScript I could do:

foobar = { "a": true, "b": true, "c": true }
keys = []
keys.push k for k,v of foobar

Which honestly isn't that much code but is there really no other way to do a set or just get the keys from an associative array without writing a special class or pulling in a separate library?

UPDATE: I have a requirement that IE < 9 needs to be supported so unfortunately Object.keys(foobar) is out. Good suggestion though, sorry I missed this req in the original question.

Upvotes: 0

Views: 1122

Answers (2)

Bergi
Bergi

Reputation: 664969

If you don't want to use Object.keys or Object.getOwnPropertyNames (or their respective shims), coffeescript offers very nice loop comprehensions:

keys = (k for own k of foobar) // == Object.keys foobar
keys = (k for k of foobar)

Upvotes: 4

jfriend00
jfriend00

Reputation: 707706

You can use Object.keys() and the polyfill here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys for browsers that don't support that.

Upvotes: 1

Related Questions