1

I have an array of values in Coffeescript such that:

arr = ['key1': 1, 'key2': 2, 'key3': 3]

I want to transform this array into an array of just values. Basically,

arr.map (iter) -> iter.value  # arr => [1,2,3]

=> []

I've attempted several permutations of this, but I just keep getting back an empty array. Any tips?

9
  • 2
    No, you don't have an array of such values. Arrays doesn't contain key-value pairs. What do you have? Commented Jun 29, 2012 at 20:42
  • Are you sure you didn't mean arr = {'key1': 1, 'key2': 2, 'key3': 3}? Commented Jun 29, 2012 at 20:42
  • Why can't this just be an object literal? Commented Jun 29, 2012 at 20:42
  • 2
    @Guffa: That is a perfectly valid CoffeeScript array. Commented Jun 29, 2012 at 20:50
  • 2
    @YuriAlbuquerque: Can people not read the tags? Or not notice the (iter) ->? Commented Jun 29, 2012 at 20:56

1 Answer 1

12

This is a CoffeeScript question and the sample code is valid CoffeeScript

arr = ['key1': 1, 'key2': 2, 'key3': 3]

translates to the following JavaScript:

var arr;
arr = [
  {
    'key1': 1,
    'key2': 2,
    'key3': 3
  }
];

Firstly, you have to realize that

obj = 
  key1: 1 
  key2: 2
  key3: 3

is most likely what you want.

Then you can use the following code to create an array with only the values of the object.

arr = null
arr.push val for key, val of obj

Update

This one-liner from 'mu is too short' is even better.

arr = (val for key, val of obj)
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you for reading the tags. I'd probably go with values = (v for own k,v of obj) or values = (v for k,v of obj) though.
+1 He did not mention in his question it was CofeeScript until after some time which is why confusion was there.
Sorry, I'm a bit new to StackOverflow. I tagged the question with CoffeeScript, and I had assumed that most people look at the tags. I unfortunately included JavaScript.
I got to the question through the CoffeeScript tag that's how I knew, but there are a lot more people that answer JavaScript-tagged questions so I can understand the confusion.
@muistooshort I tried a comprehension before, but my syntax was wrong. I had better read the documentation a little better. Thank you for a CoffeeScript solution.
|

Your Answer

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