I have an object which im converting into an array of coords which will be used to store which coords are “occupied”.
I thought i had it working but on further inspection through console.log the array is missing a fair few results.
So this is basically my object:
var sdata = {"4":{"7":["1","7","3","3"]}};
In words this is:
var sdata = {"X":{"Y":["ID","ID","Width","Height"]}
Ignore ID for this as they are unrelated… but im trying to use this data so that i have the X and Y + the additional X and Y coords related to its tile dimensions width and height.
Imagine if you will the object for 4:7 is 3 by 3 dimensions so resulting in these 9 grid references would exist.
[4:7], [5:7], [6,7]
[4:8], [5:8], [6,8]
[4:9], [5:9], [6:9]
So my function to create the coords is :
function populate_collisions() {
for (var X in sdata) {
X = parseInt(X);
for (var Y in sdata[X]) {
Y = parseInt(Y);
width = parseInt(sdata[X][Y][2]);
height = parseInt(sdata[X][Y][3]);
for (i=X; i!= X+width; i++) {
if( typeof gcollision[i] == 'undefined' ) {
gcollision[i] = new Array();
}
gcollision[i][Y] = 1
for (j=Y; j!=Y+height; j++) {
if( typeof gcollision[X] == 'undefined' ){
gcollision[X] = new Array();
}
gcollision[X][j] = 1
}
}
}
}
}
But my logic must be wrong because im getting this result for my array:
[4] [7] = 1
[4] [8] = 1
[4] [9] = 1
[5] [7] = 1
[6] [7] = 1
Any idea why im missing additional data?
Here’s the fixed code:
In the next part, you were using
X, which is always 4 so you were just overwriting that array. Useiinstead ofX.You don’t need the if test, since the array is created above, unless you really meant
gcollision[X][j]or similar. I don’t know as I don’t know the structure you want for thegcollisionobject.For the record, the resulting object (assuming
gcollisionhas no other properties) is:All those nulls don’t exist, the arrays are sparse, but that’s how JSON represents them.