Reputation: 119
So I have
var arrays = [
[ Material A, 1, 2, 3, 4, 5 ],
[ Material B, 6, 7, 8, 9, 10 ],
[ Material C, 11, 12, 13, 14, 15 ]
];
and I need to put it in this format which is a multidimensional associative array,
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 }
];
I am trying
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
}
}
But so far it is not working when I try to store the first "Name": "MaterialA" . What am I doing wrong or can this even be done? Thanks for the help.
Upvotes: 1
Views: 1173
Reputation: 12079
This is working for me. Notice I removed the [0]
from your bigdata[i][0]
, and added the row assignment code to your "j" loop.
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/
Upvotes: 2
Reputation: 56769
The proper way to set a property of an associative array/object is like this:
bigdata[i]["Property"] = value // this allows dynamic property name
bigdata[i].Property = value // or like this, if property is hard-coded
So in your case, it should be:
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];
Here is a demo: http://jsfiddle.net/56tk5/
Upvotes: 1