简体   繁体   English

如何在Javascript中动态正确填充关联数组

[英]How to correctly populate an associative array dynamically in Javascript

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]. 我正在尝试在数组中构建数组,我希望能够通过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. 我下面有一个示例代码,我无法按自己的方式工作,我想知道是否有人可以发现问题。

$.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]));

});

The structure of the fetched JSON data is as shown here: 提取的JSON数据的结构如下所示:

{
    "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,
    {}]
}​

The code above doesn't seem to store values to the array within the test array as alert(Object.keys(test[1])) doesn't give anything (ie just blank alert). 上面的代码似乎没有将值存储到测试数组中的数组中,因为alert(Object.keys(test[1]))并没有给出任何结果(即只是空白警报)。

Edit: after the mistakes spotted by Oleg V. Volkov (below): 编辑:在Oleg V. Volkov(如下)发现的错误之后:

$.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]));

});

Still not working. 还是行不通。

var cat = data[key];

You don't need this line. 您不需要此行。 Your data is already in value . 您的数据已经value

You're overwriting same test[l] values on each iteration, so in the end you will only have result of the last outermost iteration in it - in many browsers that will be one that goes over "5": ["Regulation", 0, {}] key/value pair. 您在每次迭代中都覆盖了相同的test[l]值,因此最后您只能得到最后一次最外层迭代的结果-在许多浏览器中,它们将超过"5": ["Regulation", 0, {}]键/值对。 Quick look over you code suggest cat[2] will be {} for it and that so last iteration will overwrite anything in test[] with empty objects. 快速查看您的代码,建议cat[2]适用于{} ,因此最后一次迭代将用空对象覆盖test[]所有内容。 So your keys correctly returns empty list, but you have an error in your logic. 因此,您的keys正确返回了空列表,但是逻辑上有错误。

Regarding your updated example: You're still overwriting test entries with {} because you use .inArray to check it and it will always succeed in not finding any number value in array. 关于更新后的示例:您仍在使用{}覆盖测试条目,因为使用.inArray进行了检查,并且在数组中找不到任何数字值总是成功的。 .inArray looks for a specific value, not keys/indexes. .inArray查找特定值,而不是键/索引。 You should check if specific index is empty instead with if(!test[l]) 您应该使用if(!test[l])检查特定索引是否为空if(!test[l])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM