簡體   English   中英

通過鍵刪除數組中的對象

[英]Remove object in array by key

我正在嘗試在 JavaScript 中通過鍵刪除對象

這是數組的示例

{
Account Manager: {selected: true}
Arrival: {selected: true}
Client: {selected: true}
Client Contact: {selected: true}
Created: {selected: true}
Created by: {selected: true}
Departure: {selected: true}
Destination: {selected: true}
Keywords: {selected: true}
Status: {selected: true}
}

現在我試圖從這個數組中刪除狀態和客戶端,但我不知道如何制作它。 我試過這個:

for(var i=0; i<list.length; i++) {
    if(list[i] == 'Status' || list[i] == 'Client') {
       list.splice(i, 1);
    }
}

提供的示例是Object而不是array 由於您使用的是AngularJS您可以直接使用JavaScript從對象中刪除鍵。

以下是簡單使用delete()方法的示例

 const _object = { "Account Manager": { selected: true }, "Arrival": { selected: true }, "Client": { selected: true }, "Client Contact": { selected: true }, "Created": { selected: true }, "Created by": { selected: true }, "Departure": { selected: true }, "Destination": { selected: true }, "Keywords": { selected: true }, "Status": { selected: true } } delete _object["Status"]; console.log(_object);

我們可以使用 reduce 函數 -:

let newList = Object.keys(oldList).reduce((acc, key) => {
    if(key !== 'Status' || key !== 'Client'){
        acc[key] = oldList[key]
    }
    return acc;
}, {})

我們可以使用delete關鍵字 -:

delete object["keyName"];

這將刪除該特定鍵...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM