简体   繁体   中英

Why does filter returns the same array?

I need to remove an item using filter, but it returns the same array... Im new to react.. so pls keep that in mind with the answers :)

* method *

removeItemHandler = (id) => {
    if (this.state.selectedProducts.length <= 0){
      return
    }
      let carsSelected = this.state.selectedProducts.filter(item => {
        return item !== id})
        debugger;
        console.log(`item removed`, carsSelected);}

debugger (clicked 3 items)

  removeItemHandler = (id) => { ***id = {id: 2, name: "Bugatti", price: 3200000, description: "Extremely Fast", total: 0, …}
***
    if (this.state.selectedProducts.length <= 0){
      return
    }
      let carsSelected = this.state.selectedProducts.filter(item => ***{ carsSelected = (3) [{…}, {…}, {…}]***

        return item !== id}) ***id = {id: 2, name: "Bugatti", price: 3200000, description: "Extremely Fast", total: 0, …}***
        debugger;

console.log returns the same array

You should filter by item.id instead of item

let carsSelected = this.state.selectedProducts.filter(item => item.id !== id.id)
//                                                                 ^^

Note that you are passing an object as id parameter. And you are comparing two objects. This is not easily done in JavaScript. Object equality is not how it seems. For example:

var firstObject = {
    id: 1,
    foo: "foo",
    bar: "bar"
};

var secondObject = {
    id: 1,
    foo: "foo",
    bar: "bar"
};


console.log(firstObject === secondObject); // with triple "="
// Output: false

console.log(firstObject == secondObject);  // with double "="
// Output: false

Even both objects have the same properties with same values, they are not same objects.

Instead of comparing whole objects, you can compare their unique identifiers

For further reading: Object comparison in JavaScript

您需要将商品的ID与传递给您的ID进行比较以进行过滤。

let carsSelected = this.state.selectedProducts.filter(item => { return item.id !== id.id});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM