javascript 将 JSON 对象成员字符串值连接在一起
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12043865/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Join JSON Object member string values together
提问by 0pt1m1z3
"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.
我解析了上面的 JSON(使用 .ajax 和 jsonp 作为回调),我想将“name”的所有值加入一个字符串。即“狗,猫,羊”。我怎样才能做到这一点?我已经尝试过对“类别”和名称的简单连接,即
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.
但是由于我们正在查看它的成员及其字符串值,因此它不起作用。
回答by Rocket Hazmat
This looks like a job for $.map
!
这看起来像是一份工作$.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(', ');
回答by Bar?? U?akl?
var text = "";
for(var i=0; category.length; i++)
{
text += category[i].name;
if(i!=category.length-1)
text += ", ";
}