How to retrieve a array/object data values using HOF?

Does anybody can help me how to retrieve array/object values using High Order Functions?

this is my data, the block repeats several times and I need to retrieve the resident names.

species: [
    {
      id: lionId,
      name: 'lions',
      popularity: 4,
      location: 'NE',
      availability: ['Tuesday', 'Thursday', 'Saturday', 'Sunday'],
      residents: [
        {
          name: 'Zena',
          sex: 'female',
          age: 12,
        },
     etc

I have tried the following code, but only can get the residents group, and I need to extract only residents names.

return species.map((e) => e.residents);

1 answer

  • answered 2021-11-27 12:00 Emiel Zuurbier

    Your map method will return an array of arrays with resident objects inside of it. Use flatMap to flatten the data to a single array of resident objects.

    Then map over the resident objects and return the name property for each resident. This will give you an array of resident names.

    const species = [{
      id: '',
      name: 'lions',
      popularity: 4,
      location: 'NE',
      availability: ['Tuesday', 'Thursday', 'Saturday', 'Sunday'],
      residents: [{
        name: 'Zena',
        sex: 'female',
        age: 12,
      }, ],
    }];
    
    const residents = species.flatMap(specie => specie.residents);
    const residentNames = residents.map(resident => resident.name);
    console.log(residentNames);

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum