简体   繁体   English

通过键值从数组中查找和删除对象

[英]Find and delete Object from Array by Key Value

This is very similar to existing threads but not quite the same: 这与现有线程非常相似,但不完全相同:

Find object by id in an array of JavaScript objects 通过ID在JavaScript对象数组中查找对象

From this thread I know that I can find an Object via $.grep : 从这个线程我知道我可以通过$.grep找到一个对象:

var events = [
                {startTime: 5, endTime: 20}, 
                {startTime: 15, endTime: 22}, 
                {startTime: 30, endTime: 31}
             ];

var results = $.grep(events, function(e){ 
   return (e.startTime == 15 && e.endTime == 22); });
return results[0]; // 1 result guaranteed

But how would I remove this found object from the events array? 但是,如何从事件数组中删除找到的对象? In order to use splice , do I need an index along with $.grep ? 为了使用splice ,我是否需要一个索引以及$.grep

I need to find the Object in the Array by Key/Value, and then remove it. 我需要通过键/值在数组中找到对象,然后将其删除。

 var events = [ {startTime: 5, endTime: 20}, {startTime: 15, endTime: 22}, {startTime: 30, endTime: 31} ]; var results = $.grep(events, function(e){ return (e.startTime == 15 && e.endTime == 22); }); console.log(results[0]); //console.log(events); // 1 result guaranteed 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

var events = [
    {startTime: 5, endTime: 20}, 
    {startTime: 15, endTime: 22}, 
    {startTime: 30, endTime: 31}
];

var filteredEvents = events.filter(function(item) {
    return item.prop !== undersirableValue;
});

more info here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter 此处提供更多信息https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

Just use filter and negate the search 只需使用过滤器并取消搜索

 var events = [{ startTime: 5, endTime: 20 }, { startTime: 15, endTime: 22 }, { startTime: 30, endTime: 31 } ]; events = events.filter(e => !(e.startTime == 15 && e.endTime == 22)); console.log(events); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM