为了账号安全,请及时绑定邮箱和手机立即绑定

如何在比较另一个对象的同时过滤对象数组?

如何在比较另一个对象的同时过滤对象数组?

忽然笑 2021-06-29 09:47:48
我正在尝试搜索汽车列表(具有品牌、型号、价格和其他值),并将其与我在表单中搜索的汽车进行比较。我知道如何准确比较两辆车,但我不知道如何过滤它,例如,我只想按品牌搜索并显示相同品牌的所有汽车(但不用担心其他值,因为没有选择其他值)。我试过使用 lowdash ._isEqual(),如果两个对象完全相同,它就会起作用。但是,如果我只想按某个品牌或某个年份或类似的东西搜索,我不知道该怎么做。app.component.tsexport 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      })    })  }}输入form.component.tsexport 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);  } }汽车服务.tsexport class CarsService {  constructor() {}  getAllCars() {    return of(Cars);  }}
查看完整描述

3 回答

?
跃然一笑

TA贡献1826条经验 获得超6个赞

试试下面的


this.cars.filter(c => {

        return c.make == this.make // You can have multiple conditions here

})

Filter方法返回满足条件的新数组中的项目。


查看完整回答
反对 回复 2021-07-08
?
烙印99

TA贡献1829条经验 获得超13个赞

你只需要告诉 filter 函数你想在你的数组中检查什么条件,它会返回你的条件变为真的每个元素,例如,如果你想通过 make 过滤:


this.cars.filter(c => {

    c.make === 'SOME_MAKE'

});

您还可以添加多个过滤器:


this.cars.filter(c => {

    c.make === 'SOME_MAKE' && c.year === 2015  // Filtering by make and year

});


查看完整回答
反对 回复 2021-07-08
  • 3 回答
  • 0 关注
  • 183 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信