我想计算成本,我从过去1小时开始就停滞不前。这是我的数据
Todo: [{
name: "primary",
items: [{
item: 'Todo itme #1',
isDone: false,
cost: 0
}]
}, {
name: "Secondary",
items: [{
item: 'Todo itme #1',
isDone: false,
cost: 0
}]
}]
我想循环所有项目并计算总费用。
但我无法解决它。
items数组中的条目可以动态增加。
请指导!
答案 0 :(得分:3)
Array#reduce
解决方案。
let Todo = [{
name: "primary",
items: [{
item: 'Todo itme #1',
isDone: false,
cost: 3
}, {
item: 'Todo itme #2',
isDone: false,
cost: 2
}]
}, {
name: "Secondary",
items: [{
item: 'Todo itme #3',
isDone: false,
cost: 1
}]
}],
totalCost = Todo.reduce((s,a) => {
return s + a.items.reduce((s,a) => s + a.cost, 0);
}, 0);
console.log(totalCost);

答案 1 :(得分:2)
您只想计算总和的结果?然后试试这个:
var sum = 0;
var Todo = [{
name: "primary",
items: [{
item: 'Todo itme #1',
isDone: false,
cost: 35
}]
}, {
name: "Secondary",
items: [{
item: 'Todo itme #1',
isDone: false,
cost: 10
}]
}];
Todo.forEach(function(todo) {
todo.items.forEach(function(item) {
sum += item.cost
});
});
console.log(sum)

答案 2 :(得分:0)
此代码不会花费时间来使用它并搜索它,我总是使用它
componentDidMount() {
let i=0;
let cost = 0;
let Todo = [
{name:"primary",items:[{item:'Todo itme #1',isDone:false,cost:20}]},
{name:"Secondary",items:[{item:'Todo itme #2',isDone:false,cost:5}]},
];
Todo.map(function( itemElement ){
let itemElement2 = itemElement.name;
let item =itemElement.items;
return [itemElement2, item];
}).filter(function(value){
if (typeof value[0] === 'string'){
console.log( "name " +value[0] )
}
if(typeof value[1] === "object") {
console.log(
"item in items : item " + i +" "+
value[1][0].item + " "+
value[1][0].isDone + " "+
value[1][0].cost
);
cost+=parseInt(value[1][0].cost);
console.log(' cost '+cost)
}
return value ;
});
}