javascript - 如何通过数组的数组内的属性过滤数组
问题描述
我试图establishments
通过是否在数组本身specialCategories
的数组中找到来过滤数组中的每个建立。establishmentSpecials
establishments
我可以establishmentSpecials
为每个机构过滤阵列,但我想保留机构部分,如图所示。
//masterEstablishments array is from the db
//The categories array, to filter out all but the following
specialCategories = ["Breakfast Special"];
//The array to hold the filtered establishments
var establishments;
//For all Establishments
for(var i=0;i<masterEstablishments.length;i++){
//Filter out Catorgory from establishmentSpecials where Category is not found in specialCategories
establishments = masterEstablishments[i].establishmentSpecials.filter(x => specialCategories.includes(x.Category));
}
console.log("Filtered establishments");
console.log(establishments);
总而言之,例如
var establishments = [ {address: "55 Garden rd"},
[{Category: "Breakfast Special"}, {Category: "Dinner Special"}]
];
应该成为
establishments = [ {address: "55 Garden rd"},
[{Category: "Breakfast Special"}]
];
因为“晚餐特价”不在特殊类别中
specialCategory = [{Category: "Breakfast Special"}]
非常感谢。
解决方案
您是说您只是想删除场所中的{Category: "Dinner Special"}?
specialCategories = ["Breakfast Special"];
const establishments = establishments.map((element) => {
return {
Cuisine_Type: element.Cuisine_type,
Address: element.Address, // add the other properties so on and so forth
establishmentSpecials : element.establishmentSpecials.map((ES_element) =>{
if (ES_element.Category === specialCategories[0]) {
return ES_element;
}
})});
推荐阅读
- android - 如果视图在直接父视图的边界之外进行动画处理,则 onTouchListener() 没有响应
- ios - 在单元格中加载时隐藏/显示@IBOUlet @IBAction
- c - 从 txt 文件中读取 3 维数组
- javascript - 如何在电子上管理 CPU 密集型任务
- android - 使用没有清单的主题 - 尽管声明了主题,但应用程序崩溃
- python - 从 pyqtgraph.image 图中获取对应的 x,y,z 值
- excel - 在 Excel VBA 函数中使用用户输入的公式?
- asp.net-mvc - 如何首先使用代码计算 mvc5 中年龄之间的值
- matlab - MATLAB - padarray()
- javascript - 使用故障画布屏幕截图作为 p5 图像背景