[英]How can I filter through an array of objects while also comparing another object?
I'm trying to search through a list of cars (which have a make, model, price, and other values) and compare it to the car I am searching for on my form. 我正在尝试搜索汽车列表(包含品牌,型号,价格和其他值)并将其与我在表单上搜索的汽车进行比较。
I know how to do it where I compare the two cars exactly, but I'm not sure how to filter it when I, for example, only want to search by make and show all the cars by the same make (but not worry about the other values since nothing else was selected). 我知道怎么做才能完全比较两辆车,但我不知道如何过滤它,例如,我只想通过make搜索并显示所有车辆的相同品牌(但不用担心)其他值因为没有其他选择)。
I've tried using the lowdash ._isEqual()
, which worked if the two objects are exactly the same. 我尝试过使用lowdash
._isEqual()
,如果这两个对象完全相同的话就可以使用。 But, I have no idea how to do it if I only want to search by a certain make, or only a certain year, or something like that. 但是,如果我只是想通过某个品牌,或者某个年份,或类似的东西来搜索,我不知道该怎么做。
app.component.ts app.component.ts
export class AppComponent {
cars:Car[];
title = 'car-dealership';
constructor(private carsService:CarsService) {}
searchCars(car:Car) {
this.carsService.getAllCars().subscribe(resp => {
this.cars = resp;
this.cars.filter(c => {
//do something
})
})
}
}
input-form.component.ts 输入form.component.ts
export class InputFormComponent implements OnInit {
@Output() searchCars: EventEmitter<any> = new EventEmitter();
make:string;
year:number;
color:string;
sunRoof = false;
fourWheel = false;
lowMiles = false;
powerWindows = false;
navigation = false;
heatedSeats = false;
price:number;
constructor() { }
ngOnInit() {
}
onSubmit() {
const selectedCar = {
color: this.color,
hasHeatedSeats: this.heatedSeats,
hasLowMiles: this.lowMiles,
hasNavigation: this.navigation,
hasPowerWindows: this.powerWindows,
hasSunroof: this.sunRoof,
isFourWheelDrive: this.fourWheel,
make: this.make,
price: Number(this.price),
year: Number(this.year)
}
console.log('form submitted with:', selectedCar);
this.searchCars.emit(selectedCar);
}
}
cars.service.ts cars.service.ts
export class CarsService {
constructor() {}
getAllCars() {
return of(Cars);
}
}
The filter
method just needs to return if the item should be included - if it returns true
(or any other "truthy" value) the item is included, and excluded otherwise. 如果要包含该项,则只需要返回
filter
方法 - 如果它返回true
(或任何其他“truthy”值),则包含该项,否则排除。
searchCars(car:Car) {
this.carsService.getAllCars().subscribe(resp => {
this.cars = resp.filter(c => {
return c.make === this.make; // Or whatever complicated logic you want to use
});
});
}
From your comment, I understand that you need to check two things: 1) should this criteria be used and 2) does the item match the criteria. 根据您的评论,我了解您需要检查两件事:1)是否应使用此标准; 2)项目是否符合条件。
So, let's code that! 那么,让我们编码吧!
searchCars(car:Car) {
this.carsService.getAllCars().subscribe(resp => {
this.cars = resp.filter(c => {
// First, check if the criteria should be used
if (this.make && this.make.length > 0) {
return c.make === this.make;
}
// Return a default value if the criteria isn't being used
return true;
});
});
}
Ok, that's great. 太棒了。 But what if it needs to match zero, one, or TWO conditions?
但如果需要匹配零,一或两个条件呢?
Well, we're going to use a "trick" or "pattern" called the "early return". 好吧,我们将使用一种称为“早期回归”的“技巧”或“模式”。 Instead of checking that it matches ALL conditions and returning true, we'll check if it doesn't match EACH condition and return false:
我们将检查它是否与EACH条件不匹配并返回false,而不是检查它是否匹配所有条件并返回true。
searchCars(car:Car) {
this.carsService.getAllCars().subscribe(resp => {
this.cars = resp.filter(c => {
// First, check if the criteria should be used
if (this.make && this.make.length > 0) {
// Then, check if it doesn't match
if (c.make !== this.make) {
// Early return, it doesn't matter what the other checks say
// we know this shouldn't be included.
return false;
}
}
// First, check if the criteria should be used
if (this.color && this.color.length > 0) {
// Then, check if it doesn't match
if (c.color !== this.color) {
// Early return, it doesn't matter what the other checks say
// we know this shouldn't be included.
return false;
}
}
// Repeat for all conditions you need to look at
// Return a default value. If the code gets here it means either:
// 1) no conditions are applied
// 2) it matches all relevant conditions
return true;
});
});
}
Try the below 试试下面的内容
this.cars.filter(c => {
return c.make == this.make // You can have multiple conditions here
})
Filter method returns items in a new array which satisfies the condition. Filter方法返回满足条件的新数组中的项。
You only need to tell filter function what condition you want to check in your array, and it will return each element your condition become true, for example, if you want to filter by make: 您只需告诉过滤器函数要在数组中检查哪种条件,它将返回条件变为true的每个元素,例如,如果要按make过滤:
this.cars.filter(c => {
c.make === 'SOME_MAKE'
});
You can also add multiple filters: 您还可以添加多个过滤器:
this.cars.filter(c => {
c.make === 'SOME_MAKE' && c.year === 2015 // Filtering by make and year
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.