javascript 如何从 JSON 响应中获取逗号分隔的列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11061061/
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
How to get a comma separated list from a JSON response?
提问by jini
Hello I have a javascript question whereby I am getting a JSON result:
你好,我有一个 javascript 问题,我得到了一个 JSON 结果:
{"0":"San Diego acls","1":"San Diego pals","2":" San Diego CPR","3":" Temecula acls","4":" Temecula pals"}
which is stored in a variable called data.
它存储在一个名为 data 的变量中。
I want to parse this data variable and make a list like:
我想解析这个数据变量并制作一个列表,如:
San Diego acls, San Diego pals, San Diego CPR, Temecula acls, Temecula pals
Any elegant ways?
有什么优雅的方法吗?
Thanks
谢谢
回答by UltraInstinct
What you need is this:
你需要的是这个:
var res = [];
for (var x in obj)
if (obj.hasOwnProperty(x))
res.push(obj[x]);
console.log(res.join(","));
And there's one more way of 'elegantly' doing it (taken from Alex's answer),
还有另一种“优雅”的方式(取自亚历克斯的回答),
res = [];
Object.keys(obj).forEach(function(key) {
res.push(obj[key]);
});
console.log(res.join(","));
In case you need the result in that specific order, sorting the keys (that come from Object.keys(obj)
) before invoking forEach on the array will help. Something like this:
如果您需要按特定顺序获得结果,Object.keys(obj)
在对数组调用 forEach 之前对键(来自)进行排序会有所帮助。像这样的东西:
Object.keys(obj).sort().forEach(function(key) {
回答by Hassan
This is very simple in Javascript. You can access the variable data
like this:
这在 Javascript 中非常简单。您可以data
像这样访问变量:
alert(data[0]);
which should alert "San Diego acls". Do the same for all of them using a loop. You can concatenate strings easily with the +
operator.
这应该提醒“圣地亚哥 acls”。使用循环对所有这些都做同样的事情。您可以使用+
运算符轻松连接字符串。
var result = "";
for (var dString in data) {
result += dString + ", ";
}
This will create a string called result
and add the elements of the strings in the array to it. It will also add ", " between each element as you described in the question.
这将创建一个名为result
的字符串并将数组中字符串的元素添加到其中。它还会在您在问题中描述的每个元素之间添加“,”。
回答by Bob
This one also works.
这个也有效。
$(document).ready(function(){
var data = {"0":"San Diego acls","1":"San Diego pals","2":" San Diego CPR","3":" Temecula acls","4":" Temecula pals"};
var csv = $.map(data,function(data){ return data;});
alert(csv);
});