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

我正在尝试搜索汽车列表(具有品牌、型号、价格和其他值),并将其与我在表单中搜索的汽车进行比较。


我知道如何准确比较两辆车,但我不知道如何过滤它,例如,我只想按品牌搜索并显示相同品牌的所有汽车(但不用担心其他值,因为没有选择其他值)。


我试过使用 lowdash ._isEqual(),如果两个对象完全相同,它就会起作用。但是,如果我只想按某个品牌或某个年份或类似的东西搜索,我不知道该怎么做。


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

      })

    })

  }

}

输入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);

  } 

}

汽车服务.ts


export class CarsService {


  constructor() {}


  getAllCars() {

    return of(Cars);

  }

}


忽然笑
浏览 184回答 3
3回答

跃然一笑

试试下面的this.cars.filter(c => {&nbsp; &nbsp; &nbsp; &nbsp; return c.make == this.make // You can have multiple conditions here})Filter方法返回满足条件的新数组中的项目。

烙印99

你只需要告诉 filter 函数你想在你的数组中检查什么条件,它会返回你的条件变为真的每个元素,例如,如果你想通过 make 过滤:this.cars.filter(c => {&nbsp; &nbsp; c.make === 'SOME_MAKE'});您还可以添加多个过滤器:this.cars.filter(c => {&nbsp; &nbsp; c.make === 'SOME_MAKE' && c.year === 2015&nbsp; // Filtering by make and year});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript