Blankman
Blankman

Reputation: 267190

how to build a string of id's from a json object

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

Upvotes: 0

Views: 442

Answers (3)

Tomalak
Tomalak

Reputation: 338326

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"

Upvotes: 3

Kamil Szot
Kamil Szot

Reputation: 17817

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(',')

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630569

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(',');

Upvotes: 2

Related Questions