簡體   English   中英

從對象的 javascript 列表中刪除對象

[英]Removing an object from a javascript list of objects

我目前在 javascript 中有一個由鍵索引的對象列表:

var list = [];
list['a'] = [];
list['a'].push({obj: 'test'});
list['a'].push({obj: 'test2'});

list['b'] = [];
list['b'].push({obj: 'test'});
list['b'].push({obj: 'test2'});

我會列出刪除基於鍵的條目 (a/b)

我嘗試了以下方法:

for(var x in list) { delete list[x]; }

這有效,但它實際上在列表中留下了一個未定義的條目。

我也嘗試過拼接數組,但在這種情況下似乎不起作用。

關於如何刪除 javascript 或 jQuery 中的條目的任何想法?

謝謝。

修復:

在閱讀了一些評論后,我能夠更好地理解我的列表是一致的。 因此,我能夠通過執行以下操作來進行刪除:

delete list.b;

我不確定我的列表是否是組織結構的最佳方式,但是在列表上進行刪除並將其視為對象屬性就可以了。

感謝所有的反饋。

我假設list是一個對象,而不是一個數組。

如果您想重置a或(或b它做了同樣的方式)

list.a.length = 0;

如果你想從刪除元素a已知指數(讓index

list.a.splice(index, 1);

您正在嘗試將元素作為對象屬性添加到數組對象而不是數組元素 您可以通過檢查list.length的值來驗證這list.length (將為0)。

因此,在執行以下操作時:

function removeProperty(id) {
    if (list.hasOwnProperty(id)) {
      delete list[id];
  }
}

removeProperty('a');

它真的是一樣的:

delete list.a;

這就是為什么你認為它在'列表'中留下一個未定義的'條目'

您需要使用文字對象:

var list = {};

list['a'] = [];
...

list['b' = [];
...

這將允許您使用delete並使其行為符合您的預期。 當然你會丟失陣列上的.length屬性但是你從來沒有這樣做過。

var list = {1: [{},{}], 2: [{},{}]};

function removeProperty(obj, prop){
    if(obj[prop]){
        delete obj[prop];
    }
}

removeProperty(list,"1");

console.log(list);

如果這個引用:

我會列出基於密鑰刪除條目(a / b)

意味着您要根據鍵(a / b)選擇要考慮的列表,然后刪除列表中的元素(或所有這些元素),您可以嘗試這樣做:

var list = [];
list['a'] = [];
list['a'].push({obj: 'test4'});
list['a'].push({obj: 'test5'});

list['b'] = [];
list['b'].push({obj: 'test'});
list['b'].push({obj: 'test2'});

var toRemove = 'test4';
var removeFrom = "a";

var consideredList;
for (var prop in list) {
  if (prop == removeFrom) {
    consideredList = list[prop];
  }
}

//Remove everything from the considered list
consideredList.splice(0, consideredList.length);

//Remove based off value, if you know the property  name
// for(var pos in consideredList) {
//   if(consideredList[pos].obj == toRemove) {
//     consideredList.splice(pos, 1);
//   }
// }

我做了幾個不同情況的Plunker (檢查script.js文件)。 對你所追求的東西似乎有點混亂,希望這對你有所幫助。 祝好運。

為 Array 類創建一個簡單的原型

Array.prototype.remove = function() {
    // Helper function to remove a single element from a list if exists
    item = arguments[0]
    if (this.includes(item)) {
        index = this.indexOf(item)
        this.splice(index, 1)
     }
}

// Now we can call
myList.remove(YourObject)

上面的代碼會將remove方法添加到您的所有列表中,因此這不僅可以幫助您處理對象,還可以幫助您處理字符串、整數或任何數據類型

暫無
暫無

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

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