1

I want to construct an array of objects programmatically. The end result I am expecting is this

[{"nickname":"xxx"},{"nickname":"yyy"},{"nickname":"zzz"}]

This is my code

@tagged_user_array = []
//pingUsers is the array which stored the list or nicknames 'xxx', 'yyy' and 'zzz'
$.each @pingUsers, (index, nick) =>
   @tagged_user_array.push(nick)

With my code above, I am unable to get my expected result. What do I need to modify in order to get my expected result?

0

2 Answers 2

2

Since you're using CoffeeScript and loops are expressions in CoffeeScript, you could use a comprehension instead:

pingUsers = ["xxx", "yyy", "zzz"]
tagged_user_array = ({nickname: value} for value in pingUsers)

Demo: http://jsfiddle.net/ambiguous/w4ugV/1/

1
  • super small tweak... remove the semi-colon. :-) Commented May 17, 2012 at 17:09
1

Try this:

var pingUsers = ["xxx", "yyy", "zzz"];
var tagged_user_array = [];

$.each(pingUsers, function(index, value)  {
    tagged_user_array.push({ "nickname" : value });
});

Example fiddle

I'm not sure why you have prefixed your variables with @ as this is invalid in javascript.

1
  • The @s, lack of parentheses, lack of var, and (...) => indicate CoffeeScript. Commented May 17, 2012 at 15:44

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.