亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在比較另一個對象的同時過濾對象數組?

如何在比較另一個對象的同時過濾對象數組?

忽然笑 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 關注
  • 192 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號