I asked a similar question here: How to remove and save object from Array
It worked when I just needed to check the type of the object ("Group" or "Organization") However I need to get more specific now and need to find objects by ID and remove / re-add them into the Array.
However when I try to adapt the code to check for an Object's id, I either can't find and remove the ID or I end up removing all the Objects from the Array.
// re-add Group to networks (This works great)
if (isChecked === 'checked') {
var group_obj = {
'id': name
}
networks.push(group_obj);
// remove Group from networks (Problem exist in the else if)
} else if (isChecked === undefined) {
var group_obj = {
'id': name
}
var removeItem = group_obj;
var obj;
networks = $.grep(networks, function(o,i) {
console.log('removeItem.id = '+removeItem.id);
console.log('name = '+name);
if (removeItem.id === name) {
obj = o;
return true;
}
return false;
}, true);
}
console.log(networks);
Console
What my networks Array looks like before I take action on the checkboxes:
[Object, Object, Object]
0: Object
count: 1
id: 6
label: "Who"
type: "Organization"
1: Object
id: 12622
2: Object
id: 13452
When the checkbox to the corresponding group is unchecked, the current code above will remove all Objects from the Array are removed instead of just the specified group object.
[]
When the checkbox is then checked again, the selected group will enter the Array.
I also tried this at first:
var obj;
networks = $.grep(networks, function(o,i) {
return o.id === name ? ((obj = o), true) : false;
}, true);
However again it does not find and remove the Object in the array with the specified id (name
) but it leaves the networks Array untouched.
How would you write the else if
statement to correct remove just the Object with the specified id and leave the rest of the Objects in the Array?