Javascript – Accessing nested array elements.

javascriptjson

I'm trying to access an element located in a cell inside of an array, that's inside of another array.

I've tried several methods but everything returns undefined.

json:

[
 {"assignment":"Tom" , "cell":["Tom", "2013-10-06", "Client 3", "Activity", "Scheduled" ]}
]

jquery:

$.getJSON('data/gridData1.json',function(json){
                var grid = json;
                filterGrid(grid, ele);
            });

This code does return an array perfectly fine.

javascript:

function filterGrid(filter, ele){
var types = ['Activity','Alert','Lead','Notification'];
var newTable = [];
var cs1 = $("option:selected", ele).attr("class");
var option = $("select[name='datagrid_filter'] option:selected").text().trim();
if(cs1 == 'type'){
    for(var i = 0; i < types.length; i++){
        if(types[i]==option){
            for(var k = 0; k < filter.length; k++){
                if(**filter[0][0][0].value==option**){
                        newTable.push(filter[k]);
                    }
                }
                break;
            }
        }
    }
buildGrid(newTable);
}

Doesn't return anything, including the first element.
Any ideas would be great, that.

Best Answer

Your array has one element, which is an object, so filter[0] gives you that object.

That object has two properties, assignment and cell, so filter[0].assignment gives you "Tom" and filter[0].cell gives you the inner array.

The inner array has filter[0].cell.length items in it, the first of which is filter[0].cell[0], the second of which is filter[0].cell[1], etc.

To iterate over the items in the inner array do this:

for(var k = 0; k < filter[0].cell.length; k++){
    if(filter[0].cell[k]==option){
        newTable.push(filter[0].cell[k]);
        break;
    }
}

...but it's kind of clunky repeating filter[0].cell everywhere, so you can add another variable that is a reference to the inner array:

var cell = filter[0].cell;
for(var k = 0; k < cell.length; k++){
    if(cell[k]==option){
        newTable.push(cell[k]);
        break;
    }
}

Your code that tried to use filter[0][0][0].value didn't work because you can't access object properties by numeric index except where the actual property name is a number, and in any case you don't want the .value bit on the end.