I have two arrays:
countriesArr:
[
{
"countryCode": "DEU",
"name": "Germany",
"companyFunctions": [
{
"name": "E-Commerce",
"companyName": "Company 1"
}
]
},
{
"countryCode": "FRA",
"name": "France",
"companyFunctions": [
{
"name": "Shopping Centre",
"companyName": "Company 1"
},
{
"name": "Support Services",
"companyName": "Company 2"
},
{
"name": "Procurement Support",
"companyName": "Company 3"
},
{
"name": "Retail",
"companyName": "Company 3"
}
]
}
]
and filterArr:
[
{
"name": "Company 2",
"id": "32434d324-32434"
},
{
"name": "Company 3",
"id": "2643d3254-39244"
}
]
What I want to do is filter the countriesArr by looping through the countriesArr array where countriesArr.companyFunctions.companyName === filterArr.name.
I wrote the following code:
countriesArr.filter(p =>
p.companyFunctions.filter(cF =>
filterArr.filter(c => c.name === cF.companyName)
)
);
But this doesn't seem to work as it returns also the German object from countriesArr and it includes Company 1 in the companyFunctions of the French object from countriesArr while Company 1 isn't in the filterArr.
What am I doing wrong?
The desired result should look like:
[
{
"countryCode": "FRA",
"name": "France",
"companyFunctions": [
{
"name": "Support Services",
"companyName": "Company 2"
},
{
"name": "Procurement Support",
"companyName": "Company 3"
},
{
"name": "Retail",
"companyName": "Company 3"
}
]
}
]
.filter()always returns an array. And every array (empty or not) is always truthy