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

Access and extract values from doubly nested array of objects in JavaScript

I have an array of objects and within those objects is another object which contains a particular property which I want to get the value from and store in a separate array.

How do I access and store the value from the name property from the data structure below:

pokemon:Object
abilities:Array[2]
  0:Object
    ability:Object
      name:"blaze"
  1:Object
    ability:Object
      name:"solar-power"

How would I return and display the values in the name property as a nice string like

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

blaze, solar-power ?

I tried doing something like this but I still get an array and I don’t want to do a 3rd loop since that is not performant.

 let pokemonAbilities = [];
 let test = pokemon.abilities.map((poke) =>
        Object.fromEntries(
          Object.entries(poke).map(([a, b]) => [a, Object.values(b)[0]])
        )
      );

      test.map((t) => pokemonAbilities.push(t.ability));

Sample Data:

"pokemon": {
  "abilities": [
    {
      "ability": {
        "name": "friend-guard",
        "url": "https://pokeapi.co/api/v2/ability/132/"
      },
      "ability": {
        "name": "Solar-flare",
        "url": "https://pokeapi.co/api/v2/ability/132/"
      }
    }
  ]
}

Then I am doing a join on the returned array from above to get a formatted string.

It just seems like the multiple map() loops can be optimized but I am unsure how to make it more efficient.

Thank you.

>Solution :

There is no need for a loop within loop. Try this:

const pokemon = {
  abilities: [{
    ability: {
      name: 'friend-guard',
      url: 'https://pokeapi.co/api/v2/ability/132/'
    },
  }, {
    ability: {
      name: 'Solar-flare',
      url: 'https://pokeapi.co/api/v2/ability/132/'
    }
  }]
};

const pokemonAbilities = pokemon.abilities.map(item => item.ability.name).join(', ');

console.log(pokemonAbilities);
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