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

时间:2019-06-19 14:55:53

标签: javascript angular

我正在尝试搜索一系列汽车(具有制造商,型号,价格和其他值),并将其与我在表格上搜索的汽车进行比较。

我知道在精确比较两辆车的地方怎么做,但是例如,当我只想按品牌搜索并显示同一品牌的所有车时,我不确定如何过滤它。不必担心其他值,因为没有选择其他任何内容)。

我尝试使用低破折号._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
      })
    })
  }
}

input-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

export class CarsService {

  constructor() {}

  getAllCars() {
    return of(Cars);
  }
}

3 个答案:

答案 0 :(得分:0)

filter方法仅需要返回是否应包含该项目-如果它返回true(或任何其他“真实”值),则包含该项目,否则不包含。

  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
      });
    });
  }

从您的评论中,我了解到您需要检查两件事:1)是否应使用此标准,以及2)该项是否符合标准。

所以,让我们编写代码!

  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;
      });
    });
  }

好的,太好了。但是,如果需要匹配零个,一个或两个条件怎么办?

好吧,我们将使用称为“早期回报”的“技巧”或“模式”。我们将检查它是否与EACH条件不匹配并返回false:而不是检查它是否符合ALL条件并返回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;
      });
    });
  }

答案 1 :(得分:0)

尝试以下

const Test = styled.input`
&[type="radio"]{

  position: absolute
  &:checked:before{
      content:"";
      font: 17px/1 'Open Sans', sans-serif;
      position:absolute;
      width: 100%;
      height: 100%;
      background:orange;
      border-radius: 100%;
      left: 0;
      top: 0;
    }

}

`;

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

答案 2 :(得分:0)

您只需要告诉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
});