Search code examples
javascriptarraysslicesplice

Delete object from javascript array using variable property value


Hi all pretty new to javascript and would love some help on this problem that Im having. Basically what I am trying to do is to delete a single object from my array. The array contains objects as such: y = [{id:group}].

I would like to delete an object using the object's id, which is the first column.

What I have tried is to loop through the array to find the corresponding id and delete it, but the problem here is that the first column is not labelled "id", the first column is in id form (e.g 123).

Any help would be appreciated.

y = [{123:1},{321:2},{234:3}]
id = 123;

  for (var i = 0; i < y.length; i++)
    if (y[i].id === id) {
      y.splice(i,1);
    }
//Does not work because the first column of the object is not named "id"

Solution

  • Just check for that certain key:

    for (var i = 0; i < y.length; i++)
      if (key in y[i]) {
        y.splice(i,1);
      }
    }