查找和删除对象中的项目

时间:2012-04-25 16:19:08

标签: javascript jquery object

我有数据表使用的下面的对象,我想知道如何按名称删除项目。

实施例

假设我想从下面的对象中删除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 个答案:

答案 0 :(得分:3)

这是一个只有http://jsfiddle.net/wHkTS/

的小jsfiddle

我们的想法是遍历该区域并将您要删除的名称与当前迭代对象名称进行比较,并基本上构建一个新数组以分配回不包含您要删除的对象。

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);

答案 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';
});

答案 2 :(得分:0)

我认为你需要创建一个可以搜索然后删除它们的函数,比如

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