views:

40

answers:

3

My json object looks like:

User { ID: 234, name: 'john', ..);

I want to build a string of all the ID's.

How can I do this? is there a more elegant way than below?

var ids = '';
for(int x = 0; x < json.length; x++)
{
      ids += json[x].Id + ",";
}
// strip trailing id
+2  A: 

You can make an array, use .push() to add items and .join() the result after, like this:

var ids = [];
for(int x = 0; x < json.length; x++)
{
      ids.push(json[x].Id);
}
var idString = ids.join(',');
Nick Craver
A: 

For JavaScript 1.8 (ECMA-262 Edition 5) you might use Array.reduce to do basically the same thing:

[{id:1},{id:2},{id:3}].reduce(function(a,b) { return a+','+b.id }, '').substr(1)

If you prefer accumulating values in an array and concatenating them in the end do this:

[{id:1},{id:2},{id:3}].reduce(function(a,b) { a.push(b.id); return a }, []).join(',')

Kamil Szot
+1  A: 

Assuming you an array of several users, which is what your question seems to imply (even though the example you show is neither valid JSON nor does it indicate that there is more than one object of type user)

var jsonResult = [{ID: 1, name: 'John'}, {ID: 2, name: 'Bob'}];

var ids = jsonResult.map( function(user) {return user.ID;} ).join(',');
// ids will be "1,2"
Tomalak