我有这个对象数组,我只需要那些在给定slot_time上属性值大于0的对象,我将如何获得这样的输出。
var array = [
{ time: "10:30", slot: 3, product_Id: 77, amount: 30 }
, { time: "11:00", slot: 4, product_Id: 77, amount: 30 }
, { time: "11:30", slot: 2, product_Id: 77, amount: 30 }
, { time: "12:00", slot: 0, product_Id: 77, amount: 30 }
, { time: "12:30", slot: 0, product_Id: 77, amount: 30 }
]
输出:
booking_items: [{
"product_id": "",
"slot_time": " "
"slot_quantity": "",
"amount": "",
"sub_amount": ""
},
{
"product_id": "",
"slot_time": ""
"slot_quantity": "",
"amount": "",
"sub_amount": ""
}
]
答案 0 :(得分:-1)
我们可以使用filter()
:
var array = [
{ time: "10:30", slot: 3, product_Id: 77, amount : 30},
{ time: "11:00", slot: 4, product_Id: 77, amount : 30 },
{ time: "11:30", slot: 2, product_Id: 77, amount : 30 },
{ time: "12:00", slot: 0, product_Id: 77, amount: 30 },
{ time: "12:30", slot: 0, product_Id: 77, amount: 30 }
]
var booking_items = array.filter(obj => obj.slot > 0)
console.log(booking_items)
代码对数组中的每个对象进行检查obj.slot > 0
,并返回包含所有通过检查的对象的数组。