[英]deleting a object of an Array based on property of the object
I have an Array like this: var obj = [{x:4, y:5}, {x:6, y:2}, ...]
and I'm trying to delete one of the inside objects (properties) based on the x. 我有一个像这样的数组: var obj = [{x:4, y:5}, {x:6, y:2}, ...]
,我试图删除其中一个内部对象(属性)基于x。
this is How I'm trying to do this: 这就是我试图做到的:
obj.forEach(function (child){
if(child.x === 4){
obj.destroy(child)
}
});
But it's not working and i get 但是它不起作用,我得到了
obj.destroy is not a funtion obj.destroy不是一个功能
I also tried obj.splice(child)
but it just mess up the array. 我也尝试了obj.splice(child)
但它只是弄乱了数组。 so what am doing wrong here? 所以这是怎么了? Also is there a better way to do this by not having to loop through all of Array property every time? 还有没有比每次都遍历所有Array属性更好的方法了?
You can just use filter on the array: eg 您可以只在数组上使用过滤器:例如
let arrayToFilter = [ {x:4, y:5}, {x:6, y:2}]; const valueToFilter = 4; var filteredArray = arrayToFilter .filter((o) => { return ox !== valueToFilter; }); console.log(filteredArray);
forEach()
works on array. forEach()
在数组上工作。
If obj
is an array, you can simply use filter()
to remove the unwanted object from the array: 如果obj
是一个数组,则可以简单地使用filter()
从数组中删除不需要的对象:
var obj = [{x:4, y:5}, {x:6, y:2}] obj = obj.filter(c => cx !== 4) console.log(obj);
You perhaps, have an array as obj
because the one you posted in the question is simply invalid syntax. 您可能有一个obj
数组,因为您在问题中发布的数组只是无效的语法。
Moreover, you can use Array#findIndex
to get the index of the matching element first, and then splice
that index from the array. 此外,您可以使用Array#findIndex
首先获取匹配元素的索引,然后从数组中splice
该索引。
var obj = [{x:4, y:5}, {x:6, y:2}]; var index = obj.findIndex(item => item.x === 4); obj.splice(index, 1); console.log(obj);
i'm assuming your trying to filter out objects in an array which have an x
that matches a given value. 我假设您尝试过滤出具有x
匹配给定值的数组中的对象。 If thats the case, you should probably use the filter
method. 如果是这样,您可能应该使用filter
方法。
So assuming thats what you mean you could do the following 因此,假设这就是您的意思,您可以执行以下操作
obj = obj.filter(function (child){
if(child.x !== 4){
return obj
}
});
// shorter
obj = obj.filter( child => child.x !== 4 );
In this case, only the objects which do not have the value of 4 will be available to you in the obj
variable. 在这种情况下, obj
变量中只有不具有4值的对象才可用。 And all other objects (assuming there are no other references in your code) will be garbage collected. 所有其他对象(假设您的代码中没有其他引用)将被垃圾回收。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.