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}]

例は素晴らしいでしょう。

ありがとう

4

3 に答える 3

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);
于 2012-04-25T16:33:44.490 に答える
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';
});
于 2012-04-25T16:30:33.407 に答える
0

検索して削除できる関数を作成する必要があると思います。

function deleteByName(needle, haystack) {
 for(i in haystack) {
  if ( haystack[i].name == needle) { 
   haystack.splice(i,1);
 }
}
于 2012-04-25T16:23:23.323 に答える