Home > Software design >  Get the child element of another child element directly using map()?
Get the child element of another child element directly using map()?

Time:08-24

Using REST Countries API for a course exercise, for example all I need is the common of the name from the data, and later do common with filter() ,I write like this:

const name = countries.map((c) => c.name);
const commonName = name.map((n) => n.common);

filteredName = commonName.filter((n) => n.toLowerCase().includes(findCountry.toLowerCase()))

It works, but the variable name will not be used anymore, so maybe looks stupid?

If I write like this:

const name = countries.map((c) => c.name.map((n) => n.common);

or:

filteredName = name.common.filter((n) => n.toLowerCase().includes(findCountry.toLowerCase())) 

totally not works.

I'm new to this and have read the MDN documentation on array and map(). Just like to know if there is an obvious way to extract the common from the data to make some functions.

THANKS A LOT!!

CodePudding user response:

Map all name.common from all data (api /all).

const commonNames = fetch(`//restcountries.com/v3.1/all`)
  .then(r => r.json())
  .then(r => r.map(c => c.name.common))
  .then(names => console.log( `find Namibia: ${
      names.find(n => n === `Namibia`)}\n\nAll names:\n\n${
        names.join(`\n`)}`) );
.as-console-wrapper {
    max-height: 100% !important;
}

  • Related