最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Join JSON Object member string values together - Stack Overflow

programmeradmin0浏览0评论
"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.

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

Share Improve this question edited Aug 20, 2012 at 19:35 gen_Eric 227k42 gold badges303 silver badges342 bronze badges asked Aug 20, 2012 at 19:28 0pt1m1z30pt1m1z3 8413 gold badges12 silver badges24 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 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(', ');
var text = "";
for(var i=0; category.length; i++)
{
   text += category[i].name;
   if(i!=category.length-1)
       text += ", ";
}

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
发布评论

评论列表(0)

  1. 暂无评论