Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to filter array of object inside the array of the object type in JavaScript?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading