gpt4 book ai didi

javascript - JS过滤数组内的数组

转载 作者:行者123 更新时间:2023-11-30 07:50:57 25 4
gpt4 key购买 nike

我有一个数组如下

  [{
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
},
{
"id": 69,
"proffesional_photo": "",
"top_image": "https://sampleimage2.jpg",
"ratings": "1",
"price": 700,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}
],

当用户选择某个菜单时,需要通过它进行过滤,

每个菜品对象可能有多个menu_id,

我尝试使用 array.filter,但我无法弄清楚如何通过子数组从 Dish 数组 中进行过滤。

我尝试的代码 (filterBy = 4)

let result = data.filter(function(row) {
row.restaurant_dish_menus.filter(function(i) {
return i.menu_id == filterBy;
});
});

console.log(result) 给我一个空数组。

如果 filterBy = 4 预期的输出是

{
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}

如果 filterBy 是 3 那么两个对象都应该是输出

最佳答案

这个怎么样

var data =   [{
"id": 68,
"proffesional_photo": "",
"top_image": "https://sampleimage.jpg",
"ratings": "1",
"price": 690,
"description": null,
"type": true,
"promo": 0,
"status": true,
"item": {
"Item_name": "Dark Chocolate Latte"
},
"restaurant_dish_menus": [
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 4,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
},
{
"id": 1,
"res_dish_id": 1318,
"menu_id": 3,
"createdAt": "2018-11-13T04:28:17.000Z",
"updatedAt": "2018-11-13T04:28:17.000Z"
}
]
}];

var result = data.filter(function(m) {
return m.restaurant_dish_menus.some(function(d) {
return d.menu_id === 4;
});
})

关于javascript - JS过滤数组内的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53274128/

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