javascript多维数组

时间:2017-06-02 07:58:48

标签: javascript

我正在尝试在javascript中创建一个多维度的arrya,我可以用以下方式添加项目:

var foo = {
    "Internal": {
        "0":
        {
            "pic_id":"15011",
            "description":"Picture of a cpu",
            "localion":"img.cloudimages.us/2012/06/02/mycpu.png",
            "type":"png"
        },
            "1":{
            "pic_id":"15011",
            "description":"Picture of a cpu",
            "localion":"img.cloudimages.us/2012/06/02/mycpu.png",
            "type":"png"
        }
    },
    "External": 
    {
        "0":
        {
            "pic_id":"15014",
            "description":"Picture of a cpu",
            "localion":"img.cloudimages.us/2012/06/02/mycpu.png",
            "type":"png"
        }
    }
};

但我不知道如何将我的价值纳入主要类别。我得到了以下代码

vm.classificationNames = [,];

  for (var i = 0; i < vm.classificationNames.length; i++) {

                    vm.allGroupsInClassifications.push(vm.classificationNames[i]);
                }

            for (var i = 0; i < data.length; i++) {
                var item = data[i];

                if (item.classification != null) {

                } else if (item.classification == null) {

                   vm.classificationNames['Internal'][item];
                }
            }

            console.log(vm.classificationNames);

我也尝试使用以下内容而没有任何运气:

 vm.classificationNames['Internal'].push(item);

有谁知道我做错了什么?感谢您的帮助。

2 个答案:

答案 0 :(得分:4)

这是因为它是一个对象,而不是一个数组。 将内部对象更改为数组,push将起作用

var foo = {
    "Internal": [   // <--- Note the square braces
        {
            "pic_id": "15011",
            "description": "Picture of a cpu",
            "localion": "img.cloudimages.us/2012/06/02/mycpu.png",
            "type": "png"
        },
        {
            "pic_id": "15011",
            "description": "Picture of a cpu",
            "localion": "img.cloudimages.us/2012/06/02/mycpu.png",
            "type": "png"
        }
    ],   // <--- Note the square braces
    "External": [   // <--- Note the square braces
        {
            "pic_id": "15014",
            "description": "Picture of a cpu",
            "localion": "img.cloudimages.us/2012/06/02/mycpu.png",
            "type": "png"
        }
    ]   // <--- Note the square braces
};

foo['Internal'].push(item);

答案 1 :(得分:0)

尝试使用

迭代字典
for(var key in vm.classificationNames) {
   var entry = vm.classificationNames[entry];
   /*....*/