我有一个客户列表,每个客户都有ID,名称和项目。在物品中有价格和折扣。
我想知道的是所有用户花费的最终金额,但仅限于有折扣的商品。所以,所有商品都有折扣,然后是价格 - 折扣。
有没有办法用ES5 / ES6做到这一点?因为我可以用香草JS做,但不是很干净。
以下是代码:
UINavigationBar.appearance().barTintColor = UIColor.red
答案 0 :(得分:3)
如果我正确理解了问题,您需要所有具有折扣的用户的所有项目的总和:
let sum = clients
.reduce<{ price: number, disc: number }[]>((s, x) => s.concat(x.items), []) // flatten the item arrays
.filter(i=> i.disc > 0) // filter
.reduce((s, i)=> s + (i.price - i.disc), 0) // sum
或者如果你想要客户的物品:
let sum = clients
.map(c=> (
{
id: c.id,
name: c.name,
sumItems: c.items.filter(i=> i.disc > 0).reduce((s, x)=> s+ x.price - x.disc, 0)
}));
答案 1 :(得分:0)
不确定您是否要计算总数,但这会对您有所帮助:
过滤商品并以折扣价计算价格:
let clientsWithFilteredItems = clients.map(c => ({
id: c.id,
name: c.name,
items: c.items.filter(i => i.disc > 0).map(i => ({
priceWithDiscount: i.price - i.disc
})),
}));
let clientsWithTotalDiscountedPricePaid = clients.map(c => ({
id: c.id,
name: c.name,
totalDiscountedPrice: c.items.filter(i => i.disc > 0).reduce((total, x) => total + x.price - x.disc, 0),
}));
可执行代码段:
let clients = [
{id: 0,
name: 'John',
items: [{
price: 120,
disc: 30
},{
price: 200,
disc: 50
}]
},
{
id: 0,
name: 'Doe',
items: [{
price: 135,
disc: 0
}]
},
{
id: 0,
name: 'Matt',
items: [{
price: 150,
disc: 10
}]
}, ]
let clientsWithFilteredItems = clients.map(c => ({
id: c.id,
name: c.name,
items: c.items.filter(i => i.disc > 0).map(i => ({
priceWithDiscount: i.price - i.disc
})),
}));
let clientsWithTotalDiscountedPricePaid = clients.map(c => ({
id: c.id,
name: c.name,
totalDiscountedPrice: c.items.filter(i => i.disc > 0).reduce((total, x) => total + x.price - x.disc, 0),
}));
console.log(clientsWithFilteredItems);
console.log(clientsWithTotalDiscountedPricePaid);