javascript jQuery 循环遍历 JSON 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30181738/
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
jQuery loop through JSON array
提问by Adriaan
I have a json array which i fetch by a ajax call and would like to loop through it. The array outputs a category titel and some data records within that category. The array is as followed:
我有一个 json 数组,我通过 ajax 调用获取它并希望遍历它。该数组输出类别标题和该类别内的一些数据记录。数组如下:
{"Travel":[{"title":"Beautiful title 1"},{"title":"Beautiful title 2"},{"title":"Beautiful title 3"}],"Other":[{"title":"Beautiful title 1"}]}
The basic each function like so can't help me.
像这样的基本每个功能都帮不了我。
$.each(data, function(key, value) {
console.log(value.title);
}
I want to be able to output it with the main category title and under that have the data records shown.
我希望能够使用主类别标题输出它,并在其下显示数据记录。
So for example i want it to look like this:
例如,我希望它看起来像这样:
Travel (3 results):
旅行(3 个结果):
- Beautiful title 1
- Beautiful title 2
- Beautiful title 3
- List item
- 美丽的标题 1
- 美丽的标题 2
- 美丽的标题 3
- 项目清单
Other (1 results):
其他 (1 个结果):
- Beautiful title 1
- 美丽的标题 1
Any help would be greatly appreciated. Thank you.
任何帮助将不胜感激。谢谢你。
回答by Vigneswaran Marimuthu
var data = {"Travel":[{"title":"Beautiful title 1"},{"title":"Beautiful title 2"},{"title":"Beautiful title 3"}],"Other":[{"title":"Beautiful title 1"}]};
$.each(data, function (key, value) {
$('body').append($('<div></div>').html(key + ' (' + value.length + ' results)'));
var list = $('<ul></ul>');
$('body').append(list);
$.each(value, function (index, titleObj) {
list.append('<li>' + titleObj.title + '</li>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
回答by guest271314
Try
尝试
$.each(data, function(key, value) {
$("<ul />", {
"class": key.toLowerCase(),
"html": key + " (" + value.length + " results)<br />"
}).append($.map(value, function(title, i) {
return $("<li />", {
"html": Object.keys(title)[0] + ":" + title.title
})[0].outerHTML
})).appendTo("body");
});
var data = {
"Travel": [{
"title": "Beautiful title 1"
}, {
"title": "Beautiful title 2"
}, {
"title": "Beautiful title 3"
}],
"Other": [{
"title": "Beautiful title 1"
}]
};
$.each(data, function(key, value) {
$("<ul />", {
"class": key.toLowerCase(),
"html": key + " (" + value.length + " results)<br />"
}).append($.map(value, function(title, i) {
return $("<li />", {
"html": Object.keys(title)[0] + ":" + title.title
})[0].outerHTML
})).appendTo("body");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
回答by Shaunak D
回答by Praveen Dabral
Actually you have a Travel key their
其实你有他们的旅行钥匙
So you can do it like :
所以你可以这样做:
$.each(data.Travel,function(key, value){
console.log(value.title);
}