英文:
How can I access this property in my dictionary in js?
问题
我以为我知道如何遍历字典,但是我的循环是错误的。我尝试访问每个子项的名称,但我的代码不起作用。
这是我做的事情:
list = [
{
title: '杂货',
items: [
{
id: 4,
title: '食物',
cost: 540,
},
{
id: 5,
title: '卫生',
cost: 235,
},
{
id: 6,
title: '其他',
cost: 20,
},
],
}];
function calculateCost(){
let total = 0;
Object.keys(list).forEach((k) => { for (i in k.items) { total += i.data; } });
console.log(total);
return total;
}
英文:
I thought I understood how to loop through a dictionary, but my loop is wrong. I try to access the name of each sub item but my code does not work.
Here is what I did:
list = [
{
title: 'Groceries',
items: [
{
id: 4,
title: 'Food',
cost: 540 ,
},
{
id: 5,
title: 'Hygiene',
cost: 235,
},
{
id: 6,
title: 'Other',
cost: 20,
},
],
}];
function calculateCost(){
let total = 0;
Object.keys(list).forEach((k) => { for (i in k.items) { total += i.data; } });
console.log(total);
return total;
}
答案1
得分: 1
你的列表是一个数组,包括1个对象,而这个对象有两个属性,分别是标题和项目。这里的项目是一个对象数组,每个对象都有一个成本属性。要计算总成本,你需要循环遍历项目数组,以下是如何操作的示例代码:
let list = [
{
title: 'Groceries',
items: [
{
id: 4,
title: 'Food',
cost: 540,
},
{
id: 5,
title: 'Hygiene',
cost: 235,
},
{
id: 6,
title: 'Other',
cost: 20,
},
],
}
];
function calculateCost() {
let total = 0;
list[0].items.forEach(el => {
total += el.cost;
});
console.log(total);
return total;
}
calculateCost();
这段代码将计算总成本并在控制台输出。
英文:
Your list is an array includes 1 object and this object has two properties title and items the items here is an array of objects each one of these objects has property cost so to calculate the total cost you need to loop through items array, here is how you do it:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let list = [
{
title: 'Groceries',
items: [
{
id: 4,
title: 'Food',
cost: 540 ,
},
{
id: 5,
title: 'Hygiene',
cost: 235,
},
{
id: 6,
title: 'Other',
cost: 20,
},
],
}];
function calculateCost(){
let total = 0;
list[0].items.forEach(el => {
total += el.cost;
})
console.log(total)
return total;
}
calculateCost();
<!-- end snippet -->
答案2
得分: 1
您的list
是一个数组,而不是对象。
可以使用Array.prototype.reduce来替代Object.keys()
:
const calculateCost = (arr) => arr.reduce((tot, ob) =>
ob.items.reduce((sum, item) => sum + item.cost, tot), 0);
const list = [
{
title: 'Groceries',
items: [
{id: 4, title: 'Food', cost: 10},
{id: 5, title: 'Hygiene', cost: 20},
{id: 6, title: 'Other', cost: 30}
]
}, {
title: 'Other',
items: [
{id: 8, title: 'Scuba gear', cost: 39}
],
}
];
console.log(calculateCost(list)); // 99
英文:
Your list
is an Array, not an Object.
Instead of Object.keys() use Array.prototype.reduce:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const calculateCost = (arr) => arr.reduce((tot, ob) =>
ob.items.reduce((sum, item) => sum + item.cost, tot), 0);
const list = [
{
title: 'Groceries',
items: [
{id: 4, title: 'Food', cost: 10},
{id: 5, title: 'Hygiene', cost: 20},
{id: 6, title: 'Other', cost: 30}
]
}, {
title: 'Other',
items: [
{id: 8, title: 'Scuba gear', cost: 39}
],
}
];
console.log(calculateCost(list)); // 99
<!-- end snippet -->
答案3
得分: 1
以下是翻译好的部分:
// 拓展 @Roko 和 @mmh4all 的回答,以下代码添加了多个验证语句,以处理数据中深度嵌套属性不符合预期的情况。
const calculateCost = (orders) => {
let listOfCosts = [];
// 对于 'orders' 数组中的每个 'order' 对象,
// 将每个订单中的 'cost' 属性的值添加到 'listOfCosts' 数组中。
orders.forEach(order => {
// 如果 'order.items' 不是数组,返回。
if (!Array.isArray(order.items)) { return; }
// 使用 isNaN 和 parseFloat 处理 'cost' 属性的值。
const orderCostArr = order.items.map(item =>
isNaN(item.cost) ? 0 : parseFloat(item.cost, 10));
if (orderCostArr.length === 0) { return; }
// 将 'orderCostArr' 连接到 'listOfCosts' 数组中。
listOfCosts.push(...orderCostArr);
});
// 使用 'reduce' 方法计算 'listOfCosts' 数组中的总成本。
const totalCost = listOfCosts.reduce(
(accumulator, currentValue) => accumulator + currentValue, 0);
return totalCost;
};
const list = [
{
title: 'Groceries',
items: [
{ id: 4, title: 'Food', cost: 10 },
{ id: 3, title: 'Baked goods', cost: 20 },
{ id: 5, title: 'Hygiene', cost: 0 },
{ id: 6, title: 'Other' }
},
},
{
title: 'Gear',
items: {},
},
{
title: 'Accessories',
items: [],
},
{
title: 'Bags',
},
{
title: 'Other',
items: [
{ id: 10, title: 'Scuba gear', cost: "5" },
{ id: 8, title: 'Scuba gear', cost: "err" },
{ id: 9, title: 'Scuba gear', cost: 59 },
],
},
];
console.log(calculateCost(list)); // 94
希望这对您有所帮助。
英文:
Expanding on @Roko's and @mmh4all's answers, the following code adds several verification statements to handle cases where a deeply nested property in your data is not what you expect it to be.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const calculateCost = (orders) => {
let listOfCosts = [];
// For each 'order' object in the 'orders' array,
// add the value of the 'cost' property of each item
// in the order to 'listOfCosts' array.
orders.forEach(order => {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
if (!Array.isArray(order.items)) { return; }
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isNaN
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloat
const orderCostArr = order.items.map(item =>
isNaN(item.cost) ? 0 : parseFloat(item.cost, 10));
if (orderCostArr.length === 0) { return; }
// Concatenate 'orderCostArr' to the 'listOfCosts' array
//listOfCosts = listOfCosts.concat(orderCostArry);
// Alternate approach is to use the spread syntax (...) to
// push the items in the array returned by 'order.items.map()'
// into the 'listOfCosts' array.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
listOfCosts.push(...orderCostArr);
});
// Use the 'reduce' method on the 'listOfCosts' array
// to get the total cost.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
const totalCost = listOfCosts.reduce(
(accumulator, currentValue) => accumulator + currentValue, 0);
return totalCost;
};
const list = [
{
title: 'Groceries',
items: [
{ id: 4, title: 'Food', cost: 10 },
{ id: 3, title: 'Baked goods', cost: 20 },
{ id: 5, title: 'Hygiene', cost: 0 },
{ id: 6, title: 'Other' }
]
}, {
title: 'Gear',
items: {},
}, {
title: 'Accessories',
items: [],
}, {
title: 'Bags',
}, {
title: 'Other',
items: [
{ id: 10, title: 'Scuba gear', cost: "5" },
{ id: 8, title: 'Scuba gear', cost: "err" },
{ id: 9, title: 'Scuba gear', cost: 59 }
],
}
];
console.log(calculateCost(list)); // 94
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论