0

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?

Adrin
  • 585
  • 3
  • 11

4 Answers4

3

You can just use filter on the array: e.g.

let arrayToFilter = [ {x:4, y:5}, {x:6, y:2}];
const valueToFilter = 4;

var filteredArray = arrayToFilter .filter((o) => {
    return o.x !== valueToFilter;
});

console.log(filteredArray);
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
1

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 => c.x !== 4)
 
console.log(obj);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

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);
31piy
  • 23,323
  • 6
  • 47
  • 67
-1

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.

KooiInc
  • 119,216
  • 31
  • 141
  • 177
Ja Superior
  • 459
  • 4
  • 17