简体   繁体   English

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

[英]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.

相关问题 如何将一组对象组合到另一个对象数组中,同时还组合了公共键 - How can i combine an array of objects into another array of objects while also combining the common keys 如何使用另一个对象中的值过滤对象数组? - How can I filter an array of objects with a value from another object? 使用 ES5/Lodash,如何在不比较整个对象的情况下查找/删除一个数组中不在另一个数组中的对象? - Using ES5/Lodash, how can I find/remove objects in one array that aren't in another without comparing the whole object? 如何过滤作为对象数组中对象属性的电子邮件域? - How can I filter an email domain that is a property of an object that is in an array of objects? 如何通过以下方式过滤对象数组:如果对象 ID 是连续的 - How can I filter the array of objects by: if object ids are consective 如何遍历对象数组并将值放入过滤器中? - How can I iterate through an object array and place values into a filter? 如何根据嵌套对象数组中的键过滤对象数组? - How can I filter through an array of objects based on a key in a nested array of objects? 如何过滤对象数组并使该值与React中另一个数组的值匹配? - How do I filter through an array of objects and have that value match a value of another array in React? 除非在 javascript 数组中也满足另一个条件,否则如何过滤具有条件的项目? - How can I filter items with a condition unless another condition is also met in a javascript array? 如何在基于数组的对象数组中过滤 object 数组,并删除该 object 的属性? - How to filter an array of object inside an array of objects based on an array and also remove properties of that object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM