Javascript 基于键从对象数组中删除对象
我有一个对象数组Javascript 基于键从对象数组中删除对象,javascript,ecmascript-6,Javascript,Ecmascript 6,我有一个对象数组 arrayOfObj = [{All: true}, {Sports: true}, {Entertainment: true}] 我需要根据密钥删除一个对象。 例如,从该键具有全部属性的数组中删除对象 答案应该是: arrayOfObj = [{Sports: true}, {Entertainment: true}] 我只需要使用es6语法(如filter或find)来执行此操作 我尝试的是: const o = Object.keys(obj); this
arrayOfObj = [{All: true}, {Sports: true}, {Entertainment: true}]
我需要根据密钥删除一个对象。
例如,从该键具有全部属性的数组中删除对象
答案应该是:
arrayOfObj = [{Sports: true}, {Entertainment: true}]
我只需要使用es6语法(如filter或find)来执行此操作
我尝试的是:
const o = Object.keys(obj);
this.categoriesSelected = this.categoriesSelected.filter(r => r.o !== o);
使用过滤器并查看Object.keys是否包含不需要的键 让arrayOfObj=[{All:true},{Sports:true},{Entertainment:true}] 让unwantedKey='All'; 让res=arrayOfObj.filtere=>!Object.keyse.includesunwantedKey;
console.logres 如果阵列中没有重复的对象,那么可以使用 常量数组=[{All:true},{Sports:true},{Entertainment:true}]; const[All,…rest]=数组; console.logrest/[{Sports:true},{Entertainment:true}]您可以使用和运算符:
let arrayOfObj = [{All: true}, {Sports: true}, {Entertainment: true}]
let key= 'All';
let res = arrayOfObj.filter(o => !(key in o));
试试这个:
let arrayOfObj = [{ All: true }, { Sports: true }, { Entertainment: true }];
function removeProperty(arr, key) {
return arr.filter((obj) => Object.getOwnPropertyNames(obj)[0] != key);
}
console.log(removeProperty(arrayOfObj, 'All'));
太棒了…简单而冷静,这是行不通的。如果有两个具有所有属性的对象,会发生什么?答:它只会删除第一个:我尝试了您的代码,得到一个错误属性includes在StringType上不存在,然后您没有尝试上面的代码,或者您的数组与您显示的不同@Karty我唯一改变的是const key=Object.keysobj;我甚至试过键[0],为什么要将它设置为数组@kartysee let unwantedKey=key[0];