2013-07-01 30 views
2

這裏是我的代碼如何在javascript中刪除數組對象項?

var array = [{ id: 1, name: 'test' }, { id: 2, name: 'test2' }]; 

我需要上述陣列像下面

[{ name: 'test' }, { name: 'test2' }] 

我用delete

array.forEach(function(arr, i) { 
    delete array[i].id; 
}); 
console.log(array); 

輸出嘗試作爲

[ { id: 1, name: 'test' }, 
    { id: 2, name: 'test2'} ] 

改變但它不會刪除id項目。如何刪除數組對象項?

我在節點v0.8中使用這個。

+2

似乎工作正常:http://jsfiddle.net/AbdiasSoftware/fPJ2u/(?)在FF和Chrome中測試。沒有身份證在我的控制檯。 – K3N

+0

它似乎在螢火蟲工作正常。 – mohkhan

+0

@ Ken-AbdiasSoftware它不在客戶端,而是在服務器端使用節點** v0.8 **。 –

回答

2

id財產刪除,因爲可以證明:

for (var l in array[0]) { 
    if (array[0].hasOwnProperty(l)) { 
     console.log(array[0][l]); 
    } 
} 

jsFiddle

截圖node.js輸出:

screenshot http://testbed.nicon.nl/dump/nodejsdelx.png

+0

我在節點中使用這個,'id'沒有被刪除。 –

+0

我也在node.js中運行了它,循環只顯示'test' – KooiInc

+0

查看節點輸出的屏幕截圖。 – KooiInc

0

嗯,這裏是你的代碼與jQuery 1.9.1和d它的工作好:http://jsfiddle.net/8GVQ9/

var array = [{ id: 1, name: 'test' }, { id: 2, name: 'test2' }]; 
array.forEach(function(arr, i) { 
    delete array[i].id; 
}); 
console.log(array); 

順便說一句,你想刪除的陣列 - 這是更好地瞭解你的對象「財產」標識。

+0

我在服務器中使用此節點v0.8,其中id不會刪除。 –

0

您必須解析數組並構建新版本,然後將其替換。

var array = [{ id: 1, name: 'test' }, { id: 2, name: 'test2' }];  
var tempArray = []; 
    for(var i = 0; i < array.length; i++) 
    { 
     tempArray.push({name : array[i].name}); 
    } 
    array = tempArray; 
+0

我正在尋找解決方案,而不使用外部臨時陣列。 –

相關問題