gpt4 book ai didi

javascript - 函数中的条件选择

转载 作者:搜寻专家 更新时间:2023-10-30 22:47:16 24 4
gpt4 key购买 nike

我有以下餐厅订单对象。

   var obj = {
orders: [
null,
{
date: "2018-07-09 10:07:18",
orderVerified : true,
item: [
{
name: "apple juice",
price: 3.9,
quantity: 1,
isDrink: true
},
{
name: "Hawaii pizza",
price: 7,
quantity: 2,
isDrink: false
}
]
},
{
date: "2018-07-09 10:07:30",
orderVerified : false,
item: [
{
name: "Warmer Topfenstrudel",
price: 3.9,
quantity: 1,
isDrink: false
}
]
},
{
date: "2018-07-09 15:07:18",
orderVerified : true,
item: [
{
name: "Coca Cola 2 l",
price: 12.9,
quantity: 3,
isDrink:true
}
]
},
{
date: "2018-06-13 10:07:18",
orderVerified : true,
item: [
{
name: "Wiener Schnitzel vom Schwein",
price: 9.9,
quantity: 2,
isDrink: false
}
]
}
]
};

如果 isDrink 的值为 true,我想总结商品的价格 * 商品数量。我试过使用这个函数,它得到所有项目的总数。但我可以检查检查 isDrink 是真还是假,但我如何总结饮料价格 * 数量?

 fullTotal: function(arr) {
if (arr!=''){
return arr.reduce((sum, order) => {
return sum + order.item.reduce((itemSum, item) => (
itemSum + (item.price * item.quantity)
), 0)
},0)}
else {return 0}
},

请给我一些建议。谢谢!

最佳答案

你必须:

  • 根据您的情况从 null 值中过滤数组
  • 从非饮料中过滤项目 [property isDrink]

var obj = {
orders: [
null,
{
date: "2018-07-09 10:07:18",
orderVerified: true,
item: [{
name: "apple juice",
price: 3.9,
quantity: 1,
isDrink: true
},
{
name: "Hawaii pizza",
price: 7,
quantity: 2,
isDrink: false
}
]
},
{
date: "2018-07-09 10:07:30",
orderVerified: false,
item: [{
name: "Warmer Topfenstrudel",
price: 3.9,
quantity: 1,
isDrink: false
}]
},
{
date: "2018-07-09 15:07:18",
orderVerified: true,
item: [{
name: "Coca Cola 2 l",
price: 12.9,
quantity: 3,
isDrink: true
}]
},
{
date: "2018-06-13 10:07:18",
orderVerified: true,
item: [{
name: "Wiener Schnitzel vom Schwein",
price: 9.9,
quantity: 2,
isDrink: false
}]
}
]
};

function fullTotal(arr) {
if (arr != '') {
return arr.filter(order => order != null).reduce((sum, order) => {
return sum + order.item.filter(item => item.isDrink).reduce((itemSum, item) => (
itemSum + (item.price * item.quantity)
), 0)
}, 0)
} else {
return 0
}
}

console.log(fullTotal(obj.orders));

关于javascript - 函数中的条件选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51574177/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com