Angular 6: Remove Object from Array of Object on Conditional Based
Its very hard to remove specific conditional based object removal from Array of Objects.
So, Here is my solutions.
To do this we need to make the recursive function which calls and traverse all the child and find the specific data which match with our condition.
In this example, I want to remove data which has blank BusinessID.
So first I create a wrapper function or we can call it parent function.
[code lang=”js”] FilterData(Data: any[]) {
let tempReturn: any;
let childReturn: any;
Data.forEach(data => {
childReturn = []
if (data[‘ChildAccounts’].length > 0) {
childReturn = this.hyrarchyData(data[‘ChildAccounts’]);
}
if (data[‘BusinessID’] === ”) {
tempReturn = { ‘AccountID’: data.AccountID, ‘AccountName’: data.AccountName, ‘BusinessID’: data.BusinessID, ‘ChildAccounts’: childReturn };
} else {
tempReturn = this.simplyfyArrayToObject(childReturn);
}
if (tempReturn !== undefined && tempReturn !== null) {
this.FilteredData.push(tempReturn);
}
})
}[/code]
As we can see in this function first we are checking if the Array of Objects has child or not. If we have the child then we need to traverse the child first and then we add that child to parent object.
For the child, I explain later. but first, let’s understand the parent functionality.
After calling child function we check our condition. If it matches with our requirement then we create another object assign value to that object then push to our global variable.
Now you can see that I have created another function called “simplyfyArrayToObject”. This function just check if we have Array of Array (Nested) which we don’t want but still it creates because We have It’scondition which might not match with Parent object but match with child so in that case, it create Array of Array.
And at last we just check that if the variable exists then we simply push to Global variable.
Now come to the process of child node.
[code lang=”js”]hyrarchyData(Data: any[]) {
let tempReturn: any;
let childReturn: any;
let returnObj = [];
Data.forEach(data => {
childReturn = [];
if (data[‘ChildAccounts’].length > 0) {
childReturn = this.hyrarchyData(data[‘ChildAccounts’]);
}
if (data[‘BusinessID’] === ”) {
tempReturn = { ‘AccountID’: data.AccountID, ‘AccountName’: data.AccountName, ‘BusinessID’: data.BusinessID, ‘ChildAccounts’: childReturn };
} else {
tempReturn = this.simplyfyArrayToObject(childReturn);
}
returnObj.push(tempReturn);
});
return returnObj;
}[/code]
This function is recursive and does the same which our parent function is doing. Only the differnce is that our parent function push the value to global but this push to local varibale and return that varibal.
You can see the live demo of the complete code here