[英]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.