簡體   English   中英

使用另一個數組通過索引刪除數組中的對象

[英]Deleting objects in an array by index using another array

我有一個對象數組:

{ key : "value", key2 : "value2", key3 : "value3", key4 : "value4", key5 : "value5" }

我也有一個標准數組:

[1, 3, 5]

我將如何使用第二個數組中的值刪除第一個數組中的對象,因此我將得出以下結論:

{key2:“ value2”,key4:“ value4”}

謝謝!

事實證明,這是一個不平凡的答案,因為鍵在您的對象中沒有一致的約定。

與常規的Javascript數組不同,第一個沒有索引( key ),其余有從1開始的索引( key2key3key4 ...)。

解決此問題的最佳方法是使用ES5 Object.keys方法,並記住我們需要減去1來說明基於1的索引。

Object.keys返回所有鍵(作為作為第一個參數傳遞的值的數組)。

var obj = { hello: 0, world: 1 };
Object.keys(obj); // ['hello', 'world']

我們可以將此鍵列表與您提供的用於刪除鍵的索引一起使用。

var deletion = [1, 3, 5];
var object = { key : "value", key2 : "value2", key3 : "value3", key4 : "value4", key5 : "value5" };
var keys = Object.keys(object);

object[keys[1]] // key2
object[keys[3]] // key4
object[keys[5]] // undefined

差不多了,但是我們還沒有更正索引。 1實際上應該與數組的第一個元素有關,但是Javascript使用0代替。

object[keys[1 - 1]] // key
object[keys[3 - 1]] // key3
object[keys[5 - 1]] // key5

最后,由於Javascript 支持反射,因此我們可以使用這些鍵實時地修改對象。

就像您要從對象中刪除它們一樣,我們需要delete運算符。

刪除運算符從對象中刪除屬性。

放在一起,您將獲得:

var object = { key : "value", key2 : "value2", key3 : "value3", key4 : "value4", key5 : "value5" };
var deletion = [1, 3, 5];

var keys = Object.keys(object);

deletion.forEach(function(index) {
  delete object[keys[index - 1]];
});

編輯:但是,正如@adeneo在評論中指出的那樣

Object.keys中沒有任何順序的保證,它可以按其想要的任何順序返回鍵,這是“實現相關的”。 但是,所有瀏覽器通常都會按順序返回鍵,但這不應該依賴

這意味着您可能最終會完全刪除錯誤的密鑰 ,這最終可能是災難性的錯誤。

可以用不太健壯的方式來規避此行為。

var object = { key : "value", key2 : "value2", key3 : "value3", key4 : "value4", key5 : "value5" };
var deletion = [1, 3, 5];

function indexToKey(index) {
  return 'key' + (index > 1 ? index : '');
}

deletion.forEach(function(index) {
  delete object[indexToKey(index)];
});

此實現的健壯性較低,因為它固有地將實現與您的鍵命名結構聯系在一起。

一種簡單的方法:

 var obj = { key: "value", key2: "value2", key3: "value3", key4: "value4", key5: "value5" }; var indices = [1,3,5]; var result = removeKeys(indices, obj); alert(JSON.stringify(result, null, 4)); 
 <script> function removeKeys(indices, obj) { var index = createKeyIndex(indices); return removeIndex(index, obj); } function removeIndex(index, obj) { var keys = Object.keys(obj); var length = keys.length; var result = {}; var i = 0; while (i < length) { var key = keys[i++]; if (!index.hasOwnProperty(key)) result[key] = obj[key]; } return result; } function createKeyIndex(indices) { var length = indices.length; var index = {}; var i = 0; while (i < length) { var n = indices[i++]; var key = "key" + (n === 1 ? "" : n); index[key] = true; } return index; } </script> 

createKeyIndex函數返回鍵數組的索引對象。 它允許您測試輸入數組在O(1)時間內是否具有給定鍵。 對於長度為n的數組,創建索引需要O(n)時間。

例如, createKeyIndex([1,3,5])結果為{ key:true, key3:true, key5:true }

removeKeys函數創建給定索引數組的索引對象,然后僅添加不在給定索引數組中的那些鍵。 對於長度為m的對象,需要O(n) + O(m)時間來刪除不需要的鍵。 O(n)時間用於創建索引對象。

暫無
暫無

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

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