从数组中删除对象时得到一个空数组

Getting an empty array when removing objects from array

我的数组 (this.serviceTable) 包含一个对象,如下所示:

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

我想从该数组中删除以下内容:

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

所以结果应该是:

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

这是我试过的:

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

但是 returns 一个空数组。

你的箭头函数语法错误。如果您使用大括号,该函数不会像没有大括号那样自动 return 。过滤函数期望函数 return 是一个布尔值。

参见the docs

更正如下:

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