How to iterate through nested objects in JS

前端 未结 4 858
小鲜肉
小鲜肉 2021-02-06 14:28

Ok I\'m stumped on this one. I need to iterate through these so I can make a listing by the category so something like

Business Books

Book 1

相关标签:
4条回答
  • 2021-02-06 14:46
    jQuery.each(window.books, function(category, items) {
        alert(category);
    
        jQuery.each(items, function(idx, book) {
            alert(category + ': ' + book.Title)
        });
    });
    
    0 讨论(0)
  • 2021-02-06 14:56

    Looping with .each() is pretty easy:

    $.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 讨论(0)
  • 2021-02-06 14:59
    $.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);
            }
        });
    
    0 讨论(0)
  • 2021-02-06 15:03

    Good idea is to learn how to do it without jQuery first.

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

    0 讨论(0)
提交回复
热议问题