2012-04-25 55 views
1

我有下面的對象是由數據表使用的,我想知道如何通過名稱刪除項目。查找並從對象中刪除項目

可以說,我想從下面的對象中刪除sEcho,mDataProp_1和SSEARCH,將通過全項循環的最佳方式,並檢查文件名或是否有更簡單的方法。

[{"name":"sEcho","value":1},{"name":"iColumns","value":9}, 
{"name":"sColumns","value":""},{"name":"iDisplayStart","value":0}, 
{"name":"iDisplayLength","value":10},{"name":"mDataProp_0","value":0}, 
{"name":"mDataProp_1","value":1},{"name":"mDataProp_2","value":2}, 
{"name":"mDataProp_3","value":3},{"name":"mDataProp_4","value":4}, 
{"name":"mDataProp_5","value":5},{"name":"mDataProp_6","value":6}, 
{"name":"mDataProp_7","value":7},{"name":"mDataProp_8","value":8}, 
{"name":"sSearch","value":""},{"name":"bRegex","value":false}, 
{"name":"sSearch_0","value":""},{"name":"bRegex_0","value":false}, 
{"name":"bSearchable_0","value":false},{"name":"sSearch_1","value":""}, 
{"name":"bRegex_1","value":false},{"name":"bSearchable_1","value":false}, 
{"name":"sSearch_2","value":""},{"name":"bRegex_2","value":false}] 

例子會很棒。

感謝

回答

3

這裏有一個小小的jsfiddle可以做到這一點http://jsfiddle.net/wHkTS/

這個想法是迭代該區域,並將要刪除的名稱與當前迭代對象名稱進行比較,然後基本上構建一個新的數組以分配不包含要刪除的對象的數組。

var data = [ 
     {"name":"sEcho","value":1},{"name":"iColumns","value":9}, 
     {"name":"sColumns","value":""},{"name":"iDisplayStart","value":0}, 
     {"name":"iDisplayLength","value":10},{"name":"mDataProp_0","value":0}, 
     {"name":"mDataProp_1","value":1},{"name":"mDataProp_2","value":2}, 
     {"name":"mDataProp_3","value":3},{"name":"mDataProp_4","value":4}, 
     {"name":"mDataProp_5","value":5},{"name":"mDataProp_6","value":6}, 
     {"name":"mDataProp_7","value":7},{"name":"mDataProp_8","value":8}, 
     {"name":"sSearch","value":""},{"name":"bRegex","value":false}, 
     {"name":"sSearch_0","value":""},{"name":"bRegex_0","value":false}, 
     {"name":"bSearchable_0","value":false},{"name":"sSearch_1","value":""}, 
     {"name":"bRegex_1","value":false},{"name":"bSearchable_1","value":false}, 
     {"name":"sSearch_2","value":""},{"name":"bRegex_2","value":false} 
    ]; 

function remove(name) { 

    var arr = [], len, i; 

    // we reset len as data.length will change after erach remove 
    for(i = 0, len = data.length; i < len; i++) { 
     if (data[i].name != name) arr.push(data[i]); 
    }; 

    data = arr; 
}; 

console.log(data); 
remove('sEcho'); 
console.log(data); 
0

我認爲你需要創建一個功能,可以搜索並刪除它們,像

function deleteByName(needle, haystack) { 
for(i in haystack) { 
    if (haystack[i].name == needle) { 
    haystack.splice(i,1); 
} 
} 
1

現代ES5方法是Array.filter

var original = [{"name":"sEcho","value":1}, ... ]; 

var filtered = original.filter(function(val, index, array) { 
    var n = val.name; 
    return n !== 'sEcho' && n !== 'mDataProp_1' && n !== 'sSearch'; 
}); 
相關問題