0

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
3
  • Check out this question: stackoverflow.com/questions/759385/… Commented May 12, 2010 at 15:04
  • What type is your json variable? Commented May 12, 2010 at 15:04
  • Your object is not valid JSON, not even valid JavaScript, and even if it was - it could only contain one single ID in its current form. So what does it really look like? Commented May 12, 2010 at 15:08

3 Answers 3

3

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"
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

0

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

Comments

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.