【发布时间】:2021-08-12 11:01:35
【问题描述】:
我有一个名为 orders 的对象数组:
const orders = [
{
"order_id": 47445,
"order_type": "Wholesale",
"items": [
{
"id": 9,
"department": "Womens",
"type": "Dress",
"quantity": 4,
"detail": {
"ID": 13363,
"On Sale": 1,
}
}
]
}
];
当order_type(批发)和items.detail.ID(13363)匹配时,我需要获取数量。
到目前为止,我已经尝试了以下方法:
const result = orders.find(item => item.order_type == "Wholesale").items
.reduce((total, item) => {
if(item.detail.ID == 13363) {
return item.quantity;
}
}, 0);
result 正确返回 4 的位置
我的问题,我确信我错过了一些非常简单的事情,那就是当我的 orders 数组中有多个 items 时,它会失败。
const orders = [
{
"order_id": 47445,
"order_type": "Wholesale",
"items": [
{
"id": 9,
"department": "Womens",
"type": "Dress",
"quantity": 4,
"detail": {
"ID": 13363,
"On Sale": 1,
}
},
{
"id": 56,
"department": "Womens",
"type": "Skirt",
"quantity": 12,
"detail": {
"ID": 76884,
"On Sale": 0,
}
},
{
"id": 89,
"department": "Mens",
"type": "Shirts",
"quantity": 20,
"detail": {
"ID": 98223,
"On Sale": 1,
}
}
]
}
];
一样
const result = orders.find(item => item.order_type == "Wholesale").items
.reduce((total, item) => {
if(item.detail.ID == 13363) {
return item.quantity;
}
}, 0);
返回undefined
谢谢
【问题讨论】:
-
只能有 1 个“批发”对象,其中一个 item.detail.ID 等于 13363?或者可以有多个(您想将所有匹配的数量相加吗?)
-
正是您的最后一条评论,谢谢尼克。它需要允许多个并获得所有匹配数量的总和
标签: javascript arrays object nested array-filter