如何遍历 JS 中的嵌套对象 [英] How to iterate through nested objects in JS

查看:47
本文介绍了如何遍历 JS 中的嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我被这个难住了.我需要遍历这些,以便我可以按类别列出类似

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

商业书籍

第一册

第二册

第三册

烹饪书

等等.

但不知道如何遍历嵌套对象.有无jquery都可以

But couldn't figure out how to iterate through the nested objects. With or without jquery is fine

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."
       }
    ],
};

推荐答案

好的想法是先学习如何在没有 jQuery 的情况下完成.

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

然后你可以使用$.each().

这篇关于如何遍历 JS 中的嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆