Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
105
rated 0 times [  111] [ 6]  / answers: 1 / hits: 17451  / 12 Years ago, mon, august 20, 2012, 12:00:00
category: [{
id: 28,
name: Dogs
},
{
id: 14,
name: Cats
},
{
id: 878,
name: Sheep
}],


I have the above JSON parsed (using .ajax and jsonp as callback) and I would like to join all the values of name into a string. i.e. Dogs, Cats, Sheep. How can I do this? I have tried simple join on category and name, i.e.



var cats = categories.join(, );


OR



var cats = categories.name.join(, );


But since we are looking at it's members and their string values, it doesn't work.


More From » jquery

 Answers
10

This looks like a job for $.map!



var data = {
category: [{
id: 28,
name: Dogs
},
{
id: 14,
name: Cats
},
{
id: 878,
name: Sheep
}]
}

var cats = $.map(data.category, function(v){
return v.name;
}).join(', ');

[#83528] Sunday, August 19, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cruzjenseny

Total Points: 409
Total Questions: 93
Total Answers: 106

Location: Lithuania
Member since Fri, Sep 4, 2020
4 Years ago
;