Reputation: 7083
If i find values in object i want to delete those values from array.
What would be the best solution to accompolished this task ?
ctrl.js
var selectedOwners = [];
$scope.deleteOwner = function(dataItem){
var workerKey;
var fullName;
angular.forEach(selectedOwners,function(val,index){
workerKey = val.workerKey;
fullName = val.fullName;
})
if(dataItem.workeyKey === workerKey || dataItem.fullName === fullName){
selectedOwners.splice(workerKey,fullName);
}
}
Array and Object
Array selectedOwners = [{"fullName":"Johnson, Rocio","workerKey":3506},{"fullName":"Johnson, John S.","workerKey":571},{"fullName":"Johnson, Camille A.","workerKey":1368}]
Object {
"workerKey": 3506,
"fullName": "Johnson, Rocio",
}
Upvotes: 1
Views: 56
Reputation: 1768
Should be as simple as this:
var selectedOwners = [{
"fullName": "Johnson, Rocio",
"workerKey": 3506
}, {
"fullName": "Johnson, John S.",
"workerKey": 571
}, {
"fullName": "Johnson, Camille A.",
"workerKey": 1368
}];
var obj = {
"workerKey": 3506,
"fullName": "Johnson, Rocio",
};
for (var i = 0; i < selectedOwners.length; i++) {
if (selectedOwners[i].workerKey === obj.workerKey) {
selectedOwners.splice(i, 1);
break;
}
}
Keep in mind the for loop assumes that the workerKey is unique in the array. That's is why we only need to compare on the workerKey property only and we also break out of the for loop after find a match.
Here's the loop if the workerKey is not unique:
for (var i = 0; i < selectedOwners.length; i++) {
if (selectedOwners[i].workerKey === obj.workerKey &&
selectedOwners[i].fullName === obj.fullName) {
selectedOwners.splice(i, 1);
// we need to decrement i by one because
// we just removed an element from the array
i--;
}
}
Upvotes: 2
Reputation: 3485
I think the best idea is to use just the filter array's method. No external JS dependencies.
var selectedOwners = [{"fullName":"Johnson, Rocio","workerKey":3506},{"fullName":"Johnson, John S.","workerKey":571},{"fullName":"Johnson, Camille A.","workerKey":1368}]
var item = {
"workerKey": 3506,
"fullName": "Johnson, Rocio",
}
var resultArray = selectedOwners.filter(function(i){
return !(i.fullname == item.fullname && i.workerKey == item.workerKey)
});
Upvotes: 0
Reputation: 141
You might use grep function, like below:
$scope.deleteOwner = function(dataItem){
selectedOwners = $.grep(selectedOwners, function(value) {
return value.workerKey != dataItem.workerKey
&& value.fullName!= dataItem.fullName;
});
}
Upvotes: 0
Reputation: 1182
You could use lodash _.remove which is very simple
_.remove(selectedOwners , {
"fullName": "Johnson, Rocio",
"workerKey": 3506 //where condition
});
Upvotes: 0
Reputation: 2279
Use indexOf to get the position for the splice;
Since you're passing the object as dataItem you can do as follow:
$scope.deleteOwner = function(dataItem){
selectedOwners.splice(indexOf(dataItem), 1);
}
Upvotes: 0