简体   繁体   中英

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.

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

I also tried obj.splice(child) but it just mess up the array. 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?

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.

If obj is an array, you can simply use filter() to remove the unwanted object from the array:

 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.

Moreover, you can use Array#findIndex to get the index of the matching element first, and then splice that index from the array.

 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. If thats the case, you should probably use the filter method.

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. And all other objects (assuming there are no other references in your code) will be garbage collected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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