Note:
The first section of this answer assumes you know the difference between arrays and objects in JS, and that the values you're using as keys are numbers, not strings.
First things first. Make sure that, whatever data
holds, it's a json representation of an array, and not an object literal. Try console.log(data);
, and check your console. If you see something like:
"{"1":"123"}"
Then a for
loop just won't cut it, because jPunten
is an object, not an array. An array looks like:
"[123,4342]"
Looping an object is done using a for...in
loop:
for(var property in jPunten)
{
if (jPunten.hasOwnProperty(property))
{
console.log(jPuntent[property].CARDNR);//this will work
}
}
But visit json.org for details on the JSON format, and check MDN on, for example hasOwnProperty
. MDN also has a nice list, with good documentation on each type of loop you can use in JS.
Anyway, back to the issue at hand:
Numeric keys only:
If you want to initialize a variable to a 2D array om JS, you should declare the second (inner) array inside of the main array.
In short:
var puntmap = [][];//WRONG
//should be:
var puntmap = [[]];
It makes sense, if you think about it: if []
is an array, then [][]
are two separate arrays. If one array should be part of the other, then just simply write it inside of that array:
[//an array
[]//first element in the array => an array
]
But given that you seem to be populating a sparse array (check my answer to this question, where I explain the concept of a sparse array), you might want to consider object literals, or just declaring puntmap
as any old array.
Then, populate your array like so:
var puntmap = [];
for (var i=0;i<jPunten.length;++i)
{
//create an array under key jPunten[i].CARDNR, if it doesn't exist already
puntmap[jPunten[i].CARDNR] = puntmap[jPunten[i].CARDNR] || [];
//then, assign your value
puntmap[jPunten[i].CARDNR][jPunten[i].BITNR] = jPunten[i].STATDEV;
}
String constants as keys (properties)
If this assumption (of the jPunten[i].CARDNR
etc) are numeric, is false, then do consider using an object straight off. The array will be coerced to an object anyway, only your code won't have anyone believe the length
property, and other Array methods are available...
var puntmap = {};//create object literal
for (var i=0;i<jPunten.length;++i)
{
//create an array under key jPunten[i].CARDNR, if it doesn't exist already
if (!puntmap.hasOwnProperty(jPunten[i].CARDNR))
{//if object does not have property
puntmap[jPunten[i].CARDNR] = {};//create child object literal
//or, if jPunten[i].BITNR is always numeric:
puntmap[jPunten[i].CARDNR] = [];//you can use an array here!
}
//then, assign your value as you would
puntmap[jPunten[i].CARDNR][jPunten[i].BITNR] = jPunten[i].STATDEV;
}
Now your code, because you're using object literals, won't confuse anyone, and nobody will attempt to do something like:
puntmap.slice(12,3);
Which, on an object (assoc arrray in PHP-speak) will throw an error.