I’m going nuts trying to parse get the “name” and “id” attribute of each “division” from this json into a select:
[{"division":{"name":"Solo Male","coed":false,"size":1,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":1}},{"division":{"name":"Solo Female","coed":false,"size":1,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":2}},{"division":{"name":"4 Person Male","coed":false,"size":4,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":9}},{"division":{"name":"4 Person Female","coed":false,"size":4,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":10}},{"division":{"name":"4 Person Coed","coed":true,"size":4,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-10-29T10:46:28-04:00","id":11}},{"division":{"name":"3 Person Male","coed":false,"size":3,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":6}},{"division":{"name":"3 Person Female","coed":false,"size":3,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":7}},{"division":{"name":"3 Person Coed","coed":true,"size":3,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-10-29T10:46:22-04:00","id":8}},{"division":{"name":"2 Person Male","coed":false,"size":2,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":3}},{"division":{"name":"2 Person Female","coed":false,"size":2,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-08-25T16:42:07-04:00","id":4}},{"division":{"name":"2 Person Coed","coed":true,"size":2,"created_at":"2009-08-25T16:42:07-04:00","updated_at":"2009-10-29T10:46:16-04:00","id":5}}]
Here’s my code that I cannot get to work:
jQuery.each(data, function(i,division) {
$('#squad_division').append( $('<option value="'+ division.id+'">'+ division.name +'</option>'));
I KNOW I’m just missing something simple where I’m trying to access “division.id” and “division.name” but it eludes me.
Thanks in advance if you can help.
Cheers
Because of the structure of the JSON you need to change
division.idtodivision.division.id. Here is a jsfiddle of your almost exact same code functioning properly: http://jsfiddle.net/RqwBT/1/Basically your
divisionvariable is a single key inside the array (thedatavariable) which is an object, and that object has one property:division(which has child-properties that you want to access).Notice I removed the
$()around the HTML in your append statement as it was creating unnecessary overhead.I figured this out by calling
console.log(division);inside the each function which allowed my to inspect a single array key at a time to see how I can access the object’s information. This is my standard practice when I am loading JSON from a new source.