Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


Martin Coutts
Martin Coutts
18,154 Points

Getting return of nested function

I am trying to get the value from a currency converter API, unfortunatley the way the data is brought in the value I want is within nested objects. to get around this I found a function which breaks down the nesting to get the valuer I want back

// Breaks down object nesting to access const getNestedObject = (nestedObj, pathArr) => { return pathArr.reduce((obj, key) => (obj && obj[key] !== 'undefined') ? obj[key] : undefined, nestedObj); }

So I have a function to get the value of the transfer rate, it is printing the correct values to the console but it is returning undefined. I'm sure it has something to do with the function nesting but I can't work it out.

// Gets current transfer rate from API function $getTransferRate(currency1, currency2){ const transferSelector = currency1+"_"+currency2; console.log(transferSelector); $.get( "https://free.currencyconverterapi.com/api/v6/convert?q="+transferSelector , function( data ) { const transfer = getNestedObject(data.results, [transferSelector, 'val']); console.log(transfer); return transfer; }); }