简体   繁体   English

如何使用 javascript/jquery 从嵌套列表生成嵌套 json object

[英]How to generate nested json object from nested list with javascript/jquery

I would like to generate the following object:我想生成以下 object:

var ideaBoard = {
     "Staff Retreat" : {
         "Games" : [
             {"title" : "Rockband", "details" : "1hr"},
             {"title" : "Texas Hold em", "details" : "30min"}
         ],
         "Talks" : [
             {"title" : "The Old You", "details" : "Dr. Smith"}
         ]
     }
}

from the following HTML:来自以下 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!我是循环/数组/对象的新手 - 所以我非常感谢您的帮助!

I'm using jQuery elsewhere in this project, if it helps.如果有帮助,我在这个项目的其他地方使用 jQuery。

Thanks!谢谢!

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;
});

DEMO演示

This will most likely break if you change the structure of the HTML.如果您更改 HTML 的结构,这很可能会中断。 If you have a lot of data like this, this code might also be quite slow.如果你有很多这样的数据,这段代码也可能会很慢。

To learn about the methods used, have a look at the jQuery documentation .要了解使用的方法,请查看jQuery 文档

It is not optimized, but it works:它没有经过优化,但它可以工作:

var result = {};
var node1;
var node2;
var node3;
var tmpObj = {};
$('#data > ul').each(function() {
    node1 = $(this);
    result[node1.find('.board-title').text()] = {};
    node1.find('.category-title').each(function() {
        node2 = $(this);
        result[node1.find('.board-title').text()][node2.text()] = [];
        node2.next('ul').children('li').each(function() {
            node3 = $(this);
            tmpObj = {};
            node3.children('span').each(function() {
                tmpObj[$(this).attr('class')] = $(this).text();
            });
            result[node1.find('.board-title').text()][node2.text()].push(tmpObj);
        })
    });
});
console.log(result);

How you are generating the HTML?您如何生成 HTML? If you are using PHP you could just pass the variables to JS rather than trying to read them later from HTML.如果您使用的是 PHP,您可以将变量传递给 JS,而不是稍后尝试从 HTML 读取它们。 For example if you have them in array, could use json_encode in PHP and then echo that in your page inside variables = jQuery.parseJSON(here);例如,如果您将它们放在数组中,则可以在 PHP 中使用 json_encode,然后在您的页面中回显该变量 = jQuery.parseJSON(here);

Now if you cannot do this, and you really want to read it from HTML, you should then first select the id data with $('#data') and take its children().现在,如果你不能这样做,并且你真的想从 HTML 中读取它,那么你应该首先 select 使用 $('#data') 获取 id 数据并获取其 children()。 Then use.each() for the children.然后为孩子们使用.each()。 Then put the child to object and then check its each children() with.each() and add them to your object.然后将孩子放到 object 中,然后使用.each() 检查其每个 children() 并将它们添加到您的 object 中。 If you may have more than just those levels I recommend doing a recursive function for this.如果您可能不止这些级别,我建议为此执行递归 function。

PS: I dont think its proper HTML to put Span between UL and LI. PS:我认为将跨度放在 UL 和 LI 之间的 HTML 不合适。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM