Pregunta

I'm using the _.find() methid of Lodash to find an object and I am then trying to overwrite that object, like this...

taskToUpdate = _.find($scope.tasks, {ID: myID});
taskToUpdate = {};

This finds the reference to the task perfectly, but does not set it to an empty object, it has no effect.

However, if i pick a particular property and overwrite it, it works...

taskToUpdate = _.find($scope.tasks, {ID: myID});
taskToUpdate.title = "New title";

That works fine. I have a feeling the problem here is not lodash, but my bad understanding of how objects and references are passed between functions in javascript.

¿Fue útil?

Solución

That's because you're setting the local variable taskToUpdate to an empty object, meanwhile $scope.tasks still retains the original reference to the unaltered object.

Once you have the reference to the object you can then get the indexOf.

var index = _.indexOf($scope.tasks, taskToUpdate);

And then can blank out the object reference in the $scope.tasks

$scope.tasks[index] = {};

At this point the reference in $scope.tasks will be a blank plain object, but tasksToUpdate will continue to hold the object reference. You can choose to continue to use it at this point, or not. But once you've ended all closures that have a reference to that taskToUpdate object, it will cease to exist.

My guess is that you actually want to remove the reference from $scope.tasks rather than just blanking out the object reference. You can do this many ways, but here is one:

$scope.tasks = _.without($scope.tasks, taskToUpdate);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top