Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

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