0

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.

ajorgensen
  • 4,591
  • 3
  • 17
  • 16

2 Answers2

4

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)
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979