在JavaScript中,移除具有特定字段的对象的正确方法是什么?
我可以使用以下方式包含字段:
filteredResult = filteredResult.filter(e => e.selectedFields.includes("Red"));
但是如果我想删除所有具有此字段的属性,该怎么办?文档中似乎没有“删除”的选项。
但是如果我想要移除所有拥有这个字段的属性,我应该怎么做呢?文档中好像没有“删除”的选项。
在JavaScript中,移除具有特定字段的对象的正确方法是什么?
我可以使用以下方式包含字段:
filteredResult = filteredResult.filter(e => e.selectedFields.includes("Red"));
但是如果我想删除所有具有此字段的属性,该怎么办?文档中似乎没有“删除”的选项。
但是如果我想要移除所有拥有这个字段的属性,我应该怎么做呢?文档中好像没有“删除”的选项。
只需要取反它。
filteredResult = filteredResult.filter(e => !e.selectedFields.includes("Red"))
您可以通过使用indexOf
属性来否定includes
的结果,甚至更简洁:
const arr = [1, 2, 3];
const notIncludes1 = (arr, val) => !(arr.includes(0));
const notIncludes2 = (arr, val) => arr.indexOf(val) === -1;
filteredResult = filteredResult.filter((l) => (['Red', 'Blue','Yellow'].every(y => !l.selectedFields.toLowerCase().includes(y.toLowerCase()))));
e
的值吧?也许你的意思是selectedFields.includes(e)
? - trembye.selectedFields.includes("Red')
。 - Barmar