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
evanritscher
10,209 PointsFor in and jQuery AJAX
Hello,
I'm trying to access an external API that shorten's links and print that shorted link to the page.
I'm having trouble targeting the shortened link and I'm not to sure how to get around this.
The data comes back as follows
{
errorMessage: "",
statusCode: "OK",
errorCode: "0",
results: {
http://hello?cmp=EXP:da:paid::320x50: {
hash: "B3uXHf",
shortUrl: "http://at.test.com/B3uXHf",
longUrl: "http://hello?cmp=EXP:da:paid::320x50"
}
}
}
I need to access to key "shortUrl" but the parent object ("http://hello?cmp...") changes with each request.
I think I need to use a for in loop but am having some trouble figuring out how exactly.
I attempted
$.getJSON(externalapi, longUrl, function(data){
for(var key in data){
if(data.results[key].hasOwnProperty('shortUrl'))
console.log(data.results[key].shortUrl);
}
});
What am I missing? Is there an easier way to do this?
I need to take shortUrl and save it as a variable.
1 Answer
Steven Parker
243,215 PointsIt looks like there's something missing in the data sample — quotes, perhaps? And/or an extra colon?
If my guess is right, there's also too many levels of subscripting in the references to the data. I expect the code might need to be:
for (var key in data) {
if (data[key].hasOwnProperty('shortUrl'))
console.log(data[key].shortUrl);
}
// or maybe just:
if (data.results.hasOwnProperty('shortUrl'))
console.log(data.results.shortUrl);