art vanderlay art vanderlay - 3 months ago 12
Javascript Question

jquery access the nth record in a a named JSON element

I am confused by how to access an element by number that matches a named key. My data looks like this,

item_a
lot_1
alpha : value
beta : value
charlie : value
lot_2
alpha : value
beta : value
charlie : value


and I am able to extract the set of data for item_a and I get two objects in
v
as expected using

var getMyItems="item_a";
var myJson = $.getJSON( "/jsonData.html", function(data) {
$.each(data[getMyItems], function (k, v) {


Now I would like to access just one of the sub array
lot_1 || lot_2
by array element number only, ie
[0] || [1]
.

I have tried combinations of
data[getMyItems][0]
but do not get the desired result of returning,

var getMyItems="item_a";
var myJson = $.getJSON( "/jsonData.html", function(data) {
$.each(data[getMyItems][0], function (k, v) {


var getMyItems="item_a";
var myJson = $.getJSON( "/jsonData.html", function(data) {
$.each(data[getMyItems], function (k, v) {
$.each(v[0], function (key, val) {

Answer

To get 0, you can do:

var getMyItems="item_a";
var obj = data[getMyItems][0];
var myJson obj[Object.keys(obj)[0]];