简体   繁体   中英

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 (eg 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"

You can use filter instead of a loop:

 var y = [{123:1},{321:2},{234:3}] var id = 123; y = y.filter((obj) => !obj.hasOwnProperty(id)); console.log(y); 

Just check for that certain key:

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

I make a function using two arguments (the array, the key of the object) Using forEach method inside the array I check and compare the the key given key (via argument) with an existen key in the object elements.If it is true then I use splice() method to remove the object contains the key:

 y = [{123:1},{321:2},{234:3}]; function deleteObj(arg,value){ arg.forEach(function(element){ var index=arg.indexOf(element); if(Object.keys(element)==value.toString()){ arg.splice(index,1); } }); } deleteObj(y,123); console.log(y); 

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