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 回答