I have an array as following
[{
"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"
}
]
}
],
And when the user select a certain menu it needs to be filtered through it,
Each dish objects may have more than one menu_id,
i attempted using array.filter
but i am having trouble figuring out how to filter from the Dish array
through the sub array within.
the code i attempted (filterBy = 4
)
let result = data.filter(function(row) {
row.restaurant_dish_menus.filter(function(i) {
return i.menu_id == filterBy;
});
});
console.log(result)
gives me an empty array.
if filterBy is = 4
the expected output is
{
"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"
}
]
}
And if it filterBy
is 3 then both objects should be the output
how about this
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;
});
})