如何遍历 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()
.