How to correctly populate an associative array dynamically in Javascript
<p>I am trying to build arrays within an array and I would like to be able to access the stored data through array[x][y]. I have a sample code below that I can't get to work the way I want and I wonder if anyone can spot the problem.</p>

<pre><code>$.getJSON("/data/", function(data){

    var test = {};
    var levels = [1,2,3];

    $.each(data, function(key, value){

        var cat = data[key];

        $.each(levels, function(li,l){

            var base = cat[2];
            var keys = Object.keys(base);

            if (l == 1) {

                test[l] = {};

                $.each(keys, function(ki,k){
                    test[l][k] = base[k][0];
                });
            }

        });

    });

    alert(Object.keys(test[1]));

});
</code></pre>

<p>The structure of the fetched JSON data is as shown here:</p>

<pre><code>{
    "1": ["Distribution", 0,
    {
        "9": ["Salmonella", 0,
        {}],
        "6": ["E. coli", 0,
        {
            "8": ["from pigs", 0,
            {}],
            "7": ["from humans", 0,
            {}]}]}],
    "2": ["Adhesin", 0,
    {
        "1": ["PapG", 1,
        {
            "2": ["has three subtypes:", 0,
            {
                "3": ["PapG-I", 0,
                {}],
                "4": ["PapG-II", 0,
                {}],
                "5": ["PapG-III", 0,
                {}]}]}]}],
    "3": ["Receptors", 0,
    {}],
    "4": ["Disease associations", 0,
    {}],
    "5": ["Regulation", 0,
    {}]
}​
</code></pre>

<p>The code above doesn't seem to store values to the array within the test array as <code>alert(Object.keys(test[1]))</code> doesn't give anything (i.e. just blank alert).</p>

<p><strong>Edit:</strong> after the mistakes spotted by Oleg V. Volkov (below):</p>

<pre><code>$.getJSON("/data/", function(data){

        var test = {};
        var levels = [1,2,3];

        $.each(data, function(key, value){

               // var cat = data[key];

               $.each(levels, function(li,l){

                     var base = value[2];
                     var keys = Object.keys(base);

                     if (l == 1) {

                          if ($.inArray(l,test) == -1){ 
                              test[l] = {};
                          }

                          $.each(keys, function(ki,k){
                             test[l][k] = base[k][0];
                          });
                      }

               });

        });

        alert(Object.keys(test[1]));

});
</code></pre>

<p>Still not working.</p>
