Joe Consterdine Joe Consterdine - 1 month ago 7
Javascript Question

Get JSON Object property?

I'm trying to get the property information for 'Kind' in the JSON data here:

https://www.reddit.com/r/javascript/comments/29bj6h/how_to_learn_javascript_properly/.json

I'm currently just getting 18 'undefined' printed out to the console.

Where am I going wrong?

Cheers

$(document).ready(function(){
var jsonData = $.getJSON('http://www.reddit.com/r/javascript/comments/29bj6h/how_to_learn_javascript_properly/.json');

for(var key in jsonData) {
console.log(key.kind);
}
});

Answer

$.getJSON returns a promise (more specifically, a jqXHR object which implements the promise interface), not the results of parsing the HTTP response as JSON.

Additionally, when you iterate over an object with in, the values you get will be the names of the properties as strings. These don't have kind properties.

To get to kind you need to read the value, not the property name.

It's best to avoid in for arrays though. forEach is usually a better approach.

function processResponse(parsed_data) {
    parsed_data.forEach(processItem)
}

function processItem(current_value) {
    console.log(current_value.kind);  
}

var jqXHR = $.getJSON('http://www.reddit.com/r/javascript/comments/29bj6h/how_to_learn_javascript_properly/.json');

jqXHR.done(processResponse);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>