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.

5
  • 1
    keys=Object.keys(foobar) Commented Jan 22, 2014 at 4:10
  • developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… There is a IE6+ polyfill too. Commented Jan 22, 2014 at 4:12
  • Do note for a tip: Object.keys not available for IE < 9 Commented Jan 22, 2014 at 4:12
  • Sorry I should have mentioned that i'd seen Object.keys before. Unfortunately IE < 9 is a requirement. Commented Jan 22, 2014 at 4:23
  • You may want to see this code for mimicking some set-like functionality in javascript: stackoverflow.com/questions/7958292/… Commented Jan 22, 2014 at 4:27

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.