Matthew Harwood Matthew Harwood - 8 days ago 5
Javascript Question

Remove parent object and child object if value is undefined using Array.filter(?)

Question:



How an I removal all
emailAddress
that are empty, and if no
emailAddresses
for that approval, remove that approval.


My current solution will remove approvals when emailAddress completely empty. But not when two emailAddresses are present and one is empty (see script output vs. expected output)



var request = {
approvals: [
{
type: 'media',
emailAddresses: [
{emailAddress: 'frank@gmail.com'},
]
},
{
type: 'other',
emailAddresses: [
{emailAddress: ''},
]
},
{
type: 'scope',
emailAddresses: [
{emailAddress: 'kelly@yahoo.com'},
{emailAddress: ''},
]
}
]
}
const filterOutEmptyEmails = (approval) => {
if(approval.emailAddresses.filter(x => !!x.emailAddress).length){
return true;
}

}

let output = request.approvals.filter(filterOutEmptyEmails);

console.log(JSON.stringify(output));






// EXPECTED OUTPUT:
// approval: [
// {
// type: 'media',
// emailAddresses: [
// {emailAddress: 'frank@gmail.com'},
// ]
// },
// {
// type: 'scope',
// emailAddresses: [
// {emailAddress: 'kelly@yahoo.com'},
// ]
// }
// ]
// }]


Live Code


Answer

You are not replacing approval.emailAddresses in your code - you should use:

approval.emailAddresses = approval.emailAddresses.filter(x => !!x.emailAddress);

See demo below:

var request={approvals:[{type:'media',emailAddresses:[{emailAddress:'frank@gmail.com'},]},{type:'other',emailAddresses:[{emailAddress:''},]},{type:'scope',emailAddresses:[{emailAddress:'kelly@yahoo.com'},{emailAddress:''},]}]};
                        
var filterOutEmptyEmails = (approval) => {
   approval.emailAddresses = approval.emailAddresses.filter(x => !!x.emailAddress);
  if(approval.emailAddresses.length){
    return true;  
  }
}

var output = request.approvals.filter(filterOutEmptyEmails);

console.log(JSON.stringify(output));