简体   繁体   English

从数组中删除对象的最佳方法是什么

[英]What is the best way to delete objects from Array

I am wondering if what is the best way to find all Indexes of objects in an Array and then delete them from the Array.我想知道在数组中查找所有对象索引然后从数组中删除它们的最佳方法是什么。 Currently, my code looks like as below;目前,我的代码如下所示;

  var data = _.find(group.value, function(valueItem){ return valueItem.value == filter.value });
  var index =_.indexOf(group.value,data);
  group.value.splice(index,1);

This works great, but only gets me the first index if the index is more than once.这很好用,但如果索引不止一次,我只能得到第一个索引。 So, I am looking for a method that will get me all indexes in my Array, so I can loop through in remove all所以,我正在寻找一种方法来获取数组中的所有索引,这样我就可以循环删除所有

Use filter to create a new array of objects.使用filter创建一个新的对象数组。

Based on your example this code creates new arrays based on the value (name) of each value property.根据您的示例,此代码根据每个value属性的值(名称)创建新数组。 I've wrapped the filter code in a function ( getData ) that you can call with the original array and the name you want to check as arguments.我将filter代码包装在一个函数 ( getData ) 中,您可以使用原始数组和要检查的名称作为参数调用该函数。

If there is no match the function will return an empty array.如果没有匹配项,该函数将返回一个空数组。

 const arr = [ { id: 1, value: 'bob' }, { id: 2, value: 'dave' }, { id: 3, value: 'bob' }, { id: 4, value: 'bob' } ]; function getData(arr, name) { return arr.filter(obj => obj.value === name); } console.log(getData(arr, 'bob')); console.log(getData(arr, 'dave')); console.log(getData(arr, 'mary'));

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

相关问题 通过迭代从Java脚本数组中删除元素的最佳方法是什么? - What is the best way delete elements from java script array by iterating it? 从对象数组中查找对象索引的最佳方法是什么 - javascript - What is the best way to find index of object from array of objects - javascript 遍历这个对象数组的最佳方法是什么? - What is the best way to loop through this array of objects? 减少这样一个对象数组的最佳方法是什么? - What is the best way to reduce such an array of objects? 在Javascript中创建对象数组的最佳方法是什么? - What is the best way to create an array of objects in Javascript? Javascript:从数组中删除包含带有侦听器的对象的项的最佳方法? - Javascript: Best way to delete item which contains objects with listener from array? 从对象数组中设置变量的最佳方法 - Best way to set variables from an array of objects 从 JavaScript 中的对象数组中删除的有效方法 - Efficient way to delete from an array of objects in JavaScript 检查对象数组中的任何键是否包含来自数组数组对象的值的最佳方法是什么? - What would be the best way to check if any of the keys in an array of objects contain a value from an object of arrays array? 在Angular 2中将字符串数组转换为对象数组的最佳方法是什么? - What is the best way to convert an array of strings into an array of objects in Angular 2?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM