Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like to generate the following 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:

<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.

Thanks!

like image 380
Josiah Avatar asked May 10 '26 05:05

Josiah


1 Answers

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. 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.

like image 114
Felix Kling Avatar answered May 11 '26 18:05

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!