B
B
broke2022-01-25 14:35:21
typescript
broke, 2022-01-25 14:35:21

How to recursively extract the data of an array of objects?

Hello! I have an evolves_to array from the Pokemon Species API:
61efdfcb4daf0674633106.png

I need to pull a species object from each evolves_to. How can one recursively pull from such a nested object?

I tried to write this, but something blunted on how to return data

export const getEvoChain = (chainArray: any): any => {
    console.log(chainArray)
    chainArray && chainArray.map( 
        (element: any) => {
            console.log(element.species)
            if(element.hasOwnProperty('evolves_to')){
                getEvoChain(element.evolves_to)
                
            }  
        }
    )
    
}


Thank you in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2022-01-25
boy @skrrboy

const getNestedValues = (arr, nestedKey, valKey) =>
  Array.isArray(arr)
    ? arr.flatMap(n => [ n[valKey], ...getNestedValues(n[nestedKey], nestedKey, valKey) ])
    : [];


const values = getNestedValues(arr, 'evolves_to', 'species');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question