如何使用javascript / jquery从嵌套列表生成嵌套的json对象 [英] How to generate nested json object from nested list with javascript/jquery
本文介绍了如何使用javascript / jquery从嵌套列表生成嵌套的json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想生成以下对象:
var ideaBoard = {
"Staff Retreat" : {
"Games" : [
{"title" : "Rockband", "details" : "1hr"},
{"title" : "Texas Hold em", "details" : "30min"}
],
"Talks" : [
{"title" : "The Old You", "details" : "Dr. Smith"}
]
}
}
来自以下HTML:
<div id="data">
<ul><span class="board-title">Staff Retreat</span>
<li><span class="category-title">Games</span>
<ul>
<li>
<span class="title">Rockband</span>
<span class="details">1hr</span>
</li>
<li>
<span class="title">Texas Hold em</span>
<span class="details">30min</span>
</li>
</ul>
</li>
<li><span class="category-title">Talks</span>
<ul>
<li>
<span class="title">The Old You</span>
<span class="details">Dr. Smith</span>
</li>
</ul>
</li>
</ul>
</div>
我是循环/数组/对象的新手 - 所以我非常感谢你的帮助!
I'm new to loops/arrays/objects - so I really appreciate the help!
如果有帮助的话,我在这个项目的其他地方使用jQuery。
I'm using jQuery elsewhere in this project, if it helps.
谢谢!
推荐答案
有多种方式。这是一个:
There a multiple ways. Here is one:
var ideaBoard = {}
$('#data > ul').each(function() {
var data = {}, // board data
title = $(this).find('.board-title').text(); // board title
// find categories
$(this).find('> li > .category-title').each(function() {
var category = $(this).text(), // category title
// we can use map to create the array
var category_data = $(this).next().children('li').map(function() {
var tdata = {};
// each span contains detailed data
$(this).children('span').each(function() {
tdata[this.className] = $(this).text();
});
return tdata;
}).get();
data[category] = category_data;
});
ideaBoard[title] = data;
});
如果更改HTML的结构,这很可能会中断。如果你有这么多的数据,这段代码也可能很慢。
This will most likely break if you change the structure of the HTML. If you have a lot of data like this, this code might also be quite slow.
要了解所使用的方法,请看一下 jQuery文档 。
To learn about the methods used, have a look at the jQuery documentation.
这篇关于如何使用javascript / jquery从嵌套列表生成嵌套的json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文