我有一个对象数组,
arrayOfObj = [{All: true}, {Sports: true}, {Entertainment: true}]
我需要根据键删除一个对象。
例如,从密钥具有All
的数组中删除对象。
答案应该是:
arrayOfObj = [{Sports: true}, {Entertainment: true}]
我只需要使用es6
语法(如filter或find
const o = Object.keys(obj);
this.categoriesSelected = this.categoriesSelected.filter(r => r.o !== o);
答案 0 :(得分:4)
使用过滤器并查看Object.keys是否包含不需要的密钥
let arrayOfObj = [{All: true}, {Sports: true}, {Entertainment: true}]
let unwantedKey = 'All';
let res = arrayOfObj.filter(e => ! Object.keys(e).includes(unwantedKey));
console.log(res);

答案 1 :(得分:3)
如果您的阵列没有重复的对象,那么您可以使用destructuring assignment
const array = [{All: true}, {Sports: true}, {Entertainment: true}];
const [All, ...rest] = array;
console.log(rest) // [{Sports: true}, {Entertainment: true}]

更通用的方法是使用Array.prototype.filter
方法:
const array = [{All: true}, {All: true}, {Sports: true}, {Entertainment: true}];
const filterBy = (array, key) => array.filter(el => !el[key])
const result = filterBy(array, 'All');
console.log(result) // [{Sports: true}, {Entertainment: true}]

答案 2 :(得分:0)
您可以使用Array.prototype.filter和“in”运算符:
onLangChange(langObj) {
this.lanId = this.commonService.getCurrentLanguageCode()
$( ".instartdate input, .inenddate input, .crstartdate input, .crenddate input" ).datepicker( "option", $.datepicker.regional[this.lanId]);
})
}
答案 3 :(得分:0)
试试这个:
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'));