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

Time:04-30

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

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.

CodePudding user response:

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);

  • Related