javascript多维关联数组

时间:2014-06-26 14:05:46

标签: javascript multidimensional-array

所以我有

var arrays = [
    [ Material A, 1, 2, 3, 4, 5  ],
    [ Material B, 6, 7, 8, 9, 10  ],
    [ Material C, 11, 12, 13, 14, 15  ]
];

我需要把它放在这种多维关联数组格式

var bigdata = [
    { "Name": "MaterialA", "Row1": 1, "Row2": 2, "Row3": 3, "Row4": 4, "Row5": 5 },
    { "Name": "MaterialB", "Row1": 6, "Row2": 7, "Row3": 8, "Row4": 9, "Row5": 10 },
    { "Name": "MaterialC", "Row1": 11, "Row2": 12, "Row3": 13, "Row4": 14, "Row5": 15 }
];

我正在尝试

var bigdata = new Array(3);         

for (i=0; i<3; i++)
{
    // do name
    bigdata[i][0] = {"Name" : arrays[i][0]};

    for (j=1; j<6; j++ )
    {
        // rest of that row         
    }
}

但到目前为止,当我尝试存储第一个&#34; Name&#34;:&#34; MaterialA&#34; 。我做错了什么或者甚至可以做到这一点?谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

这对我有用。请注意,我从[0]中删除了bigdata[i][0],并将行分配代码添加到“j”循环中。

for (i=0; i<3; i++)
{
    // do name
    bigdata[i] = {"Name" : arrays[i][0]};

    for (j=1; j<6; j++ )
    {
        // rest of that row
        bigdata[i]['Row' + j] = arrays[i][j];
    }
}

JSFiddle:http://jsfiddle.net/ub54S/1/

答案 1 :(得分:1)

设置关联数组/对象属性的正确方法如下:

bigdata[i]["Property"] = value   // this allows dynamic property name
bigdata[i].Property = value      // or like this, if property is hard-coded

所以在你的情况下,它应该是:

bigdata[i] = {}   // initialize a blank object
bigdata[i].Name = arrays[i][0];

for ( j=1; j<6; j++ )
    bigdata[i]["Row" + j] = arrays[i][j];

以下是演示:http://jsfiddle.net/56tk5/