javascript根据键值查找并删除数组中的对象 [英] javascript find and remove object in array based on key value

查看:37
本文介绍了javascript根据键值查找并删除数组中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试几种方法来在数组中查找对象,其中 ID = var,如果找到,则从数组中删除该对象并返回新的对象数组.

数据:

<预><代码>[{"id":"88","name":"我们开始测试"},{"id":"99","name":"男孩女孩玩得开心"},{"id":"108","name":"你真棒!"}]

我可以使用 jQuery $grep 搜索数组;

var id = 88;var 结果 = $.grep(data, function(e){返回 e.id == id;});

但是如何在 id == 88 时删除整个对象,并返回这样的数据:

数据:

<预><代码>[{"id":"99","name":"男孩女孩玩得开心"},{"id":"108","name":"你真棒!"}]

解决方案

我可以 grep id 的数组,但是如何删除 id == 88 的整个对象

简单地通过相反的谓词过滤:

var data = $.grep(data, function(e){返回 e.id != id;});

I have been trying several approaches on how to find an object in an array, where ID = var, and if found, remove the object from the array and return the new array of objects.

Data:

[
    {"id":"88","name":"Lets go testing"},
    {"id":"99","name":"Have fun boys and girls"},
    {"id":"108","name":"You are awesome!"}
]

I'm able to search the array using jQuery $grep;

var id = 88;

var result = $.grep(data, function(e){ 
     return e.id == id; 
});

But how can I delete the entire object when id == 88, and return data like this:

Data:

[
    {"id":"99","name":"Have fun boys and girls"},
    {"id":"108","name":"You are awesome!"}
]

解决方案

I can grep the array for the id, but how can I delete the entire object where id == 88

Simply filter by the opposite predicate:

var data = $.grep(data, function(e){ 
     return e.id != id; 
});

这篇关于javascript根据键值查找并删除数组中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆