const goods = [
{id:1,name:"香蕉",price:9.9,num:150,usedata:7,data:"2019:03:20"},
{id:2,name:"苹果",price:14,num:200,usedata:10,data:"2019:03:20"},
{id:3,name:"血橙",price:8.9,num:350,usedata:15,data:"2019:03:20"},
{id:4,name:"库尔勒香梨",price:11.9,num:100,usedata:7,data:"2019:03:20"},
{id:5,name:"雪莲果",price:4.6,num:550,usedata:20,data:"2019:03:20"},
{id:6,name:"蓝莓",price:15,num:55,usedata:7,data:"2019:03:20"},
{id:7,name:"牛油果",price:24.6,num:35,usedata:20,data:"2019:03:20"},
]
const items = [
{
id:3,inventory:1
},{
id:6,inventory:2
}
]
const arr = items.map(item => { // .map
const {id,inventory} = item //解构
const good = goods.find(good => good.id === id) //.find
return {
id,
name:good.name,
price:good.price,
usedata:good.usedata,
data:good.data,
inventory
}
})
console.log(arr)
/* Array(2)
0: {id: 3, name: "血橙", price: 8.9, usedata: 15, data: "2019:03:20", …}
1: {id: 6, name: "蓝莓", price: 15, usedata: 7, data: "2019:03:20", …}
length: 2 */
总价计算
/* let total = 0
for (var i = 0; i < arr.length; i++) {
total += arr[i].price * arr[i].inventory
}
console.log(total) */
const total = arr.reduce((sum,product) => sum + product.price * product.inventory,0)
console.log(total) //38.9
网友评论