简体   繁体   中英

Angular remove object from array search for key and value

I need to remove an entry from an array by searching for the id value.

The data looks like this:

data = [ { "id": "02" }, { "id": "03" } ];

And I need a method like:

remove(keyValue) {
    // do something here
}

Usage example:

remove('02');

Then it would search the id key with value "02" and remove the data so it would remove like this:

data = [ { "id": "03" } ];

How can I do this?

You could implement something like this https://stackblitz.com/edit/typescript-g3gty2

where the method remove accepts the initial array, the key and the value to remove.

function remove(data: any[], key: string, value: any) {
  return data.filter(d => d[key] !== value);
}

If you use Typescript remove quotes from property names.

data = [ { id: "02" }, { id: "03" } ];

You can use findIndex function to get the index of specific element. After you got the index you can delete the element with splice function.

remove(keyValue: String) {
 let objectIndex = this.data.findIndex(e => e.id == keyValue); 

 if(objectIndex != -1) {
  this.data.splice(objectIndex, 1); // Remove one element from array
 }

}

Works if key is "id", and if you are sure there won't be repeated values:

 var data = [ { "id": "02" }, { "id": "03" } ]; function removeVal(value) { var removeIndex = -1; data.forEach((obj, index) => { if (obj.id === value) { removeIndex = index; } }); data.splice(removeIndex, 1); console.log(data); } removeVal("02");

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