简体   繁体   中英

Remove an item from a list of objects - Typescript

I want to remove a specific object from a list. The object model looks like this:

export class Task {
  taskId: number;
  projectId: Project;
  userId: User;
  state: string;
  description: string;
}

I created a list of Task objects and I want to delete a Task that has a specific taskId.

 moveTaskInProgress(task: Task) {
    console.log('The task is in progress...');
    task.state = 'IN_PROGRESS';
    this.taskService.updateTask(task).subscribe((nbOfUpdates) => {
      console.log('Number of updates: ' + JSON.stringify(nbOfUpdates));
      this.removeItemFromAListOfTasks(task, this.openTasks);
      console.log('List of task task: ' + JSON.stringify(this.openTasks));
    });
 }

  removeItemFromAListOfTasks(task: Task, listOfTasks: Task[]) {
    let filteredList: Task[];
    filteredList = listOfTasks.filter(item => item.taskId !== task.taskId);
  }

I have a method that receive a task, call a method that updates some properties, and after that i want to delete the task from the list.
But it seems that nothing happen. Could you, please, help me with this?

Filtering an array returns a new array with a subset of the original items. It does not modify the original array.

Instead you need to splice it.

moveTaskInProgress(task: Task) {
  console.log('The task is in progress...');
  task.state = 'IN_PROGRESS';
  this.taskService.updateTask(task).subscribe((nbOfUpdates) => {
    console.log('Number of updates: ' + JSON.stringify(nbOfUpdates));
    this.removeItemFromAListOfTasks(task, this.openTasks);
    console.log('List of task task: ' + JSON.stringify(this.openTasks));
  });
}

removeItemFromAListOfTasks(task: Task, listOfTasks: Task[]) { 
  const index = listOfTasks.indexOf(task);
  if (index === -1) {
    // the task doesn't exist in the array, no need to continue
    return;
  }

  // delete 1 item starting at the given index
  listOfTasks.splice(index, 1);
}

This is assuming that the task originated from the array. Otherwise you will need to find the index:

const index = listOfTasks.findIndex(x => x.taskId === task.taskId);

You could send only the ID instead of sending the complete object.

removeItemFromAListOfTasks(id: any, listOfTasks: Task[]) {
  return listOfTasks.filter(tast => task.taskId !== id);
}

Now it can be called like

this.openTasks = this.removeItemFromAListOfTasks(task.taskId, this.openTasks);

there is spelling mistake use tasks.tasskId instead of task.


tasks: Task[]; // here I received some objects from a HTTP request. 
filteredList: Task[];
filteredList = listOfTasks.filter(item => item.taskId !== tasks.taskId);

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