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
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"
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(',');
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(',')
精彩评论