How do I add values to semi-complex JSON object?
- by Nick Verheijen
I'm fairly new to using JSON objects and I'm kinda stuck.
I've got an JSON object that was converted from this array:
Array
(
[status] => success
[id] => 1
[name] => Zone 1
[description] => Awesome zone deze..
[tiles] => Array
(
// Column for the tile grid
[0] => Array
(
// Row for the tile grid
[0] => Array
(
[tileID] => 1
[rotation] => 0
)
[1] => Array
(
[tileID] => 1
[rotation] => 0
)
// Etc..
)
[1] => Array // etc.. etc..
)
)
I use this object to render out an isometric grid for my HTML5 Canvas game. I'm building a map editor and to put more tiles on the map, i'll have to add values to this json object.
This is how I would do it in PHP:
mapData[column][row] = array(
'tileID' => 1,
'rotation' => 0
);
So my question is, how do I achieve this with a JSON object in javascript?
Thanks in advance!
Nick
Update
I've ran into an error:
can't convert undefined to object
mapDataTiles[mouseY][mouseX] = { tileID: editorSelectedTile, rotation: 0 };
This is the code i use for clicking & then saving the new tile to the JSON object. At first I though that one of my parameters was 'undefined', so i logged those to the console but they came out perfectly..
// If there is already a tile placed on these coordinates
if( mapDataTiles[mouseX] && mapDataTiles[mouseX][mouseY] )
{
mapDataTiles[mouseX][mouseY]['tileID'] = editorSelectedTile;
}
// If there is no tile placed on these coordinates
else
{
mapDataTiles[mouseX][mouseY] = { tileID: editorSelectedTile, rotation: 0 };
}
My variables have the following values:
MouseX: 5
MouseY: 17
tileID: 2
Also weird fact, that for some coordinates it does actually work and save new data to the array.
mapDataTiles[mouseY][mouseX] = { tileID: editorSelectedTile, rotation: 0 };