5
"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.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
0pt1m1z3
  • 841
  • 3
  • 12
  • 23

3 Answers3

12

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(', ');
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
1
var text = "";
for(var i=0; category.length; i++)
{
   text += category[i].name;
   if(i!=category.length-1)
       text += ", ";
}
Barış Uşaklı
  • 13,440
  • 7
  • 40
  • 66
1

Simpler, shorter version:

const category = [{
      "id": 28,
      "name": "Dogs"
  },
  {
      "id": 14,
      "name": "Cats"
  },
  {
      "id": 878,
      "name": "Sheep"
  }]
let cats = category.map((item) => {
             return item.name;
           }).join(", ");

On the first part, the map function will return a string array with the contents item.name.

[ "Dogs", "Cats", "Sheep" ]

Since on arrays we have the ability to call join that will put all the items in array together but separated by whatever we pass to the join (in this case we have ", " it will separate by a comma and a space)

In the end we have:

Dogs, Cats, Sheep
Pedro Luz
  • 2,694
  • 4
  • 44
  • 54
Swathy
  • 31
  • 1
  • 4