How to iterate through nested objects in JS

Ok, I'm at a standstill. I need to iterate over them so that I can make a list by category so something like

Business literature

Book 1

Book 2

Book 3

Cookbooks

etc..

But I could not understand how to iterate through nested objects. With or without jQuery

window.books = {
    "Business Books": [
       {
           Title: "Finance 101",
           Description: "Info for Finance 101 book goes here."
       },
       {
           Title: "Economics 123",
           Description: "Info for Economics 123 book goes here."
       },
       {
           Title: "Statistics for Beginners",
           Description: "Learn about Statistics."
       }
    ],
    "Cooking Books": [
       {
           Title: "Lowfat Treats",
           Description: "Eat a lowfat Diet"
       },
       {
           Title: "Chocolate Lovers",
           Description: "Eat a lot of chocolate"
       },
       {
           Title: "Book of Brownies",
           Description: "Stuff about Brownies"
       }
    ],
    "IT Books": [
       {
           Title: "Windows XP",
           Description: "Please go away"
       },
       {
           Title: "Linux",
           Description: "A how to guide."
       },
       {
           Title: "Unix",
           Description: "All about Unix."
       },
       {
           Title: "Mac",
           Description: "Costs too much."
       }
    ],
};
+5
source share
4 answers

A good idea is to learn how to do this without jQuery.

for(var category in window.books) {
  if(window.books.hasOwnProperty(category)) {
    console.log(category); // will log "Business Books" etc.
    for (var i = 0, j = window.books[category].length; i < j; i++) {
      console.log("Title: %s, Description: %s", window.books[category][i].Title, window.books[category][i].Description);
    }
  }
}

Then you can use $.each().

+9
source
$.each(window.books,function(k,v){   // k ==== key, v === value
        // Prints category
        console.log(k); 

        //Loops through category
        for(i=0,len=v.length;i<len;i++){
            console.log(v[i].Title);
            console.log(v[i].Description);
        }
    });
+2
source
jQuery.each(window.books, function(category, items) {
    alert(category);

    jQuery.each(items, function(idx, book) {
        alert(category + ': ' + book.Title)
    });
});
+1
source

The loop with .each () is pretty simple:

$.each(window.books, function(category, books) {                                    
    $("#books").append("<p>" + category + "</p><ul>");                              
    $.each(books, function(i, book) {                                               
        $("#books").append("<li>" + book.Title + ": " + book.Description + "</li>");
    });                                                                             
    $("#books").append("</ul>");                                                    
});                      

here is my jsFiddle

0
source

All Articles