javascript从基于具有相同对象和值的另一个数组的数组中删除 [英] javascript delete from array based on another array with same object and values

查看:58
本文介绍了javascript从基于具有相同对象和值的另一个数组的数组中删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象数组(所有相同的对象类型)。我有另一个对象类型相同的数组,我想用来告诉我要从第一个数组中删除哪些对象。除了遍历所有属性并比较它们以找到第一个数组中与第二个数组中的元素100%匹配的元素,然后从第一个数组中删除之外,还有一种简便的方法吗?

I have an array of objects (all the same object type). I have another array of the same object type in which I want to use to tell me which objects to delete from the first array. Is there an easy way to do this besides looping through all properties and comparing them to find the elements in the first array that 100% match the elements in the second array and then deleting from the first array?

我基本上是在对象数组上执行jQuery.grep(),并从此grep生成的数组中,我想从传递给它的数组中删除。

I'm basically doing a jQuery.grep() on an array of objects and the resulting array from this grep I want to delete from the array I passed into it.

推荐答案

不是使用jQuery.grep(),而是要使用 jQuery.map(),如果必须保留该对象,则返回相同的对象;如果要删除它,则返回null。

Instead of using jQuery.grep(), to obtain a new array, replace it with jQuery.map(), returning the same object if it must be kept, or null if you want to remove it.

例如,如果您的代码是

var toBeDeleted = $.grep(array, function(val) {
  return condition(val);
});

将其更改为

array = $.map( array, function(val) {
  if(condition(val))
    return null;
  return val;
});

这篇关于javascript从基于具有相同对象和值的另一个数组的数组中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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