gpt4 book ai didi

javascript - 从对象中查找和删除项目

转载 作者:行者123 更新时间:2023-11-30 10:42:32 28 4
gpt4 key购买 nike

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

例子

假设我想从下面的对象中删除 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}]

例子会很棒。

谢谢

最佳答案

这是一个可以做到这一点的小 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);

关于javascript - 从对象中查找和删除项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10319690/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com