Zhen
Zhen

Reputation: 12431

How to construct an array of objects programmatically

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?

Upvotes: 1

Views: 167

Answers (2)

mu is too short
mu is too short

Reputation: 434635

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/

Upvotes: 2

Rory McCrossan
Rory McCrossan

Reputation: 337560

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.

Upvotes: 1

Related Questions