嗯,我有一个复杂的问题。至少对我来说这很复杂。
所以我有一个数组,其中有一个数组,其中有一个数组。
并且我想根据最深数组中的属性过滤最顶层的数组。
让我说我有这个对象数组
var garages = [{
"GarageId": 1,
"GarageName": "Garage_001",
"Sections": [{
"SectionId": 1,
"Name": "Section_002",
"Cars": [{
"Id": 5,
"Model": "Bmw"
}, {
"Id": 6,
"Model": "Mercedes"
}]
}, {
"SectionId": 2,
"Name": "Section_003",
"Cars": [{
"Id": 8,
"Model": "Toyota"
}, {
"Id": 6,
"Model": "Mercedes"
}]
}]
},
{
"GarageId": 6,
"GarageName": "Garage_006",
"Sections": [{
"Id": 1,
"Name": "Section_007",
"Cars": [{
"Id": 5,
"Model": "Bmw"
}, {
"Id": 6,
"Model": "Mercedes"
}]
}, {
"Id": 2,
"Name": "Section_003",
"Cars": [{
"Id": 8,
"Model": "Toyota"
}, {
"Id": 6,
"Model": "Mercedes"
}]
}]
}
]
例如,我想检索包含现代汽车的车库清单。我该怎么做? 我已经尝试了几个小时,这就是我想出的。这可能是一段愚蠢的代码,但是我对处理这么多嵌套的数组感到困惑!
所以我的代码是这样的:
garages: any[] = [];
selectedCarModel: number: 8;
filterOnCarModel(carId) {
this.garages = getGaragesFromServed();
this.selectedCarModel = this.CarModels.find(c => c.Id == id);
let filteredArray = this.garages
.filter((garage) =>
garage.Sections).
filter((section) =>
study.Cars.find((car) => car.Id == carId));
this.garages = filteredArray;
}
感谢您的理解
答案 0 :(得分:0)
var filteredGarages = garages.filter(garage =>
garage.Sections.filter(section =>
section.Cars.filter(car => car.Model.indexOf("Bmw")>=0)
.length > 0)
.length > 0)