[英]Remove an object from the array of object based on the key
我有一個對象數組
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);
使用過濾器,查看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);
如果您的數組中沒有重復的對象,則可以使用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}]
您可以使用Array.prototype.filter和' in '運算符:
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'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.