I’m facing one issue with one of the API responses,
I have a response something like the below one.
[
{type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyName: "US"}, {type: "County", countyName: "US"}]},
{type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "German"}, {type: "County", countyName: "German"}, {type: "County", countyName: "German"}]},
{type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "Japan"}, {type: "County", countyName: "German"}, {type: "County", countyName: "German"}]},
]
it looks like an array of objects inside that have countries also the arrays of the object type. I need all the countyName in a single array for all the array of elements. like the below one type,
newNames = [US, German, Japan];
I tried something like this. but I couldn’t able to get the output. can you please help me to do this? thank you all.
let newNames = this.selectedStateList.filter(item => item.countries.forEach(item => item.countries)).map(ele => ele.countries.forEach(item => item.countries))
>Solution :
You can look through each countries object and add your data in a Set to get unique country.
const data = [ {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "US"}, {type: "County", countyName: "US"}, {type: "County", countyName: "US"}]}, {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "German"}, {type: "County", countyName: "German"}, {type: "County", countyName: "German"}]}, {type: "StateCountry", state: "AL", countries: [{type: "County", countyName: "Japan"}, {type: "County", countyName: "German"}, {type: "County", countyName: "German"}]}, ],
result = Array.from(data.reduce((r, {countries}) => {
countries.forEach(({countyName}) => r.add(countyName));
return r;
}, new Set()));
console.log(result);