我一直在尝试几种方法,如何在一个数组中找到一个对象,其中ID = var,如果找到,从数组中删除对象,并返回新的对象数组。
数据:
[
{"id":"88","name":"Lets go testing"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"}
]
我能够搜索数组使用jQuery $grep;
var id = 88;
var result = $.grep(data, function(e){
return e.id == id;
});
但是,当id == 88时,如何删除整个对象,并返回如下数据?
数据:
[
{"id":"99", "name":"Have fun boys and girls"},
{"id":"108", "name":"You are awesome!"}
]
如果你使用的是Underscore.js,很容易根据键删除对象。
例子:
var temp1=[{id:1,name:"safeer"}, // Temporary array
{id:2,name:"jon"},
{id:3,name:"James"},
{id:4,name:"deepak"},
{id:5,name:"ajmal"}];
var id = _.pluck(temp1,'id'); // Get id array from temp1
var ids=[2,5,10]; // ids to be removed
var bool_ids=[];
_.each(ids,function(val){
bool_ids[val]=true;
});
_.filter(temp1,function(val){
return !bool_ids[val.id];
});
Sift是一个功能强大的集合过滤器,可以用于这样的操作和更高级的操作。它在浏览器的客户端或Node.js的服务器端工作。
var collection = [
{"id":"88", "name":"Lets go testing"},
{"id":"99", "name":"Have fun boys and girls"},
{"id":"108", "name":"You are awesome!"}
];
var sifted = sift({id: {$not: 88}}, collection);
它支持像$in, $nin, $exists, $gte, $gt, $lte, $lt, $eq, $ne, $mod, $all, $and, $or, $nor, $not, $size, $type和$regex这样的过滤器,并努力与MongoDB集合过滤api兼容。
ES6原生解决方案:
const pos = data.findIndex(el => el.id === ID_TO_REMOVE);
if (pos >= 0)
data.splice(pos, 1);
如果你确定元素在数组中:
data.splice(data.findIndex(el => el.id === ID_TO_REMOVE), 1);
原型:
Array.prototype.removeByProp = function(prop,val) {
const pos = this.findIndex(x => x[prop] === val);
if (pos >= 0)
return this.splice(pos, 1);
};
// usage:
ar.removeByProp('id', ID_TO_REMOVE);
http://jsfiddle.net/oriadam/72kgprw5/
注意:这将就地移除项目。如果你需要一个新的数组,使用过滤器在前面的答案中提到的。
如果你使用的是Underscore.js,很容易根据键删除对象。
例子:
var temp1=[{id:1,name:"safeer"}, // Temporary array
{id:2,name:"jon"},
{id:3,name:"James"},
{id:4,name:"deepak"},
{id:5,name:"ajmal"}];
var id = _.pluck(temp1,'id'); // Get id array from temp1
var ids=[2,5,10]; // ids to be removed
var bool_ids=[];
_.each(ids,function(val){
bool_ids[val]=true;
});
_.filter(temp1,function(val){
return !bool_ids[val.id];
});
假设id是唯一的,你只需要删除一个元素拼接就可以了:
var data = [
{"id":"88","name":"Lets go testing"},
{"id":"99","name":"Have fun boys and girls"},
{"id":"108","name":"You are awesome!"}
],
id = 88;
console.table(data);
$.each(data, function(i, el){
if (this.id == id){
data.splice(i, 1);
}
});
console.table(data);