Kee*_*ing 0 javascript for-loop nested object nested-loops
如果这是我的目标:
var obj = {
bakery1: {
small: {
name: "Small cookie",
price: 0.75;
}
large: {
name: "Large cookie",
price: 3.00;
}
}
bakery2: {
small: {
name: "Small cookie",
price: 1.00;
}
large: {
name: "Large cookie",
price: 4.00;
}
}
};
Run Code Online (Sandbox Code Playgroud)
我将如何制作一个将所有价格打印到控制台的循环?
并且在打印此值时,是否有办法跟踪名称?
例如,如果输出为3.00,我将如何创建一个函数,该函数的名称与3.00价格一致?
提前致谢!
要回答您的问题:
function printPrice(obj) {
if (obj.price)
console.log(obj.name, obj.price)
else for (key in obj)
printPrice(obj[key])
}
var obj = {
"bakery1": {
"small": {
"name": "Small cookie",
"price": 0.75
},
"large": {
"name": "Large cookie",
"price": 3
}
},
"bakery2": {
"small": {
"name": "Small cookie",
"price": 1
},
"large": {
"name": "Large cookie",
"price": 4
}
}
};
printPrice(obj)Run Code Online (Sandbox Code Playgroud)
但是,对于这些类型的集合,最好使用数组。例如,我们可以做这样的事情:
var bakeries = [
{
name: 'Bakery 1',
menu: [
{name: 'small cookie', price: 0.75},
{name: 'large cookie', price: 3.00}
]
},
{
name: 'Bakery 2',
menu: [
{name: 'small cookie', price: 1.00},
{name: 'large cookie', price: 4.00}
]
}
]
Run Code Online (Sandbox Code Playgroud)
这使我们能够更好地组织每个项目的特定属性。在这种情况下,打印价格的代码变得简单得多:
bakeries
.map(bakery => bakery.menu)
.forEach(menu => menu.map(
item => console.log(item.name, item.price)))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2173 次 |
| 最近记录: |