简体   繁体   中英

Getting an empty array when removing objects from array

My array ( this.serviceTable ) includes an object, that looks like this:

[
    {
        "0": {
            "service": "Service 0"
        },
        "id": 0
    },
    {
        "1": {
            "service": "Service 1"
        },
        "id": 1
    },
    {
        "2": {
            "service": "Service 2"
        },
        "id": 2
    }
]

And from that array, I want to delete the following:

[
    {
        "2": {
            "service": "Service 2"
        },
        "id": 2
    },
    {
        "0": {
            "service": "Service 0"
        },
        "id": 0
    }
]

So the result should be:

[
    {
        "1": {
            "service": "Service 1"
        },
        "id": 1
    }
]

This is what I have tried:

const SELECTED_IDS:Array<number> = [];
for (let item of this.selection.selected) {
  SELECTED_IDS.push(item.id);
}

console.log(
  this.serviceTable.filter((serviceValue, i) => {
    !SELECTED_IDS.includes(i);
  }
), 'result');
}

But that returns an empty array.

Your arrow function syntax is wrong. If you use curly brackets the function does not automatically return anything like it does without the curly brackets. And filter function expects that the function return a boolean.

See the docs .

Here is the correction:

console.log(
  this.serviceTable.filter((serviceValue, i) => !SELECTED_IDS.includes(i)
), 'result');

// OR

console.log(
  this.serviceTable.filter((serviceValue, i) => {
    return !SELECTED_IDS.includes(i);
  }
), 'result');
}

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