Forums > Javascript

how to store multidimensional associative arrays

July 5, 2008 | 2:51 pm

hello folks,

is it possible to store an array like this with one command ?
(which is inside a javascript)

function makeMAarray(){
this.theObjectArray = new Array()
this.theObjectArray["points"] = [[1,2], [1,3], [2,4]]
this.theObjectArray["geoType"] = "polygon"
this.theObjectArray["rotation"] = 0.12425
}


July 5, 2008 | 7:37 pm

You could do:

this.theObjectArray = {
"points": [[1,2], [1,3], [2,4]],
"geoType": "polygon",
"rotation": 0.12425
}

Then you’ll have a generic object, not an Array. So you can’t call theObjectArray.length or the various Array methods like reverse(), push(), pop(), etc. You probably don’t need those for an associative array.

But if you really need an Array then you might try something like this:

function makeArray(obj) {
arr = new Array()
for(field in obj) {
arr[field] = obj[field]
}
return arr
}

theObjectArray = makeArray({
"points": [[1,2], [1,3], [2,4]],
"geoType": "polygon",
"rotation": 0.12425
})


July 5, 2008 | 8:53 pm

thanx adam. i did not explained exactly what i want to do.
sorry …
my intention was to store the array in a file on the disk.
i checked out the pattr object, colls and a jitter matrix.


July 6, 2008 | 8:51 pm

Quote: videomasta wrote on Sat, 05 July 2008 13:53
—————————————————-
> thanx adam. i did not explained exactly what i want to do.
> sorry …
> my intention was to store the array in a file on the disk.
> i checked out the pattr object, colls and a jitter matrix.
>

Cycling ’74 provides a File API for javascript so you can read and write files inside your script. That might be the easiest route. It doesn’t seem to be documented in Max 5, but in Max 4 there is a JavascriptInMax.pdf that explains in detail. It should still work in Max 5. I haven’t used it though…

Looping over an array and dumping to a file should be easy. It’s trickier if you want to read the file back in later and reconstruct the array. I think using a generic object instead of an array could simplify things, then you could use a JSON library to convert back and forth between an object and a string/file. See for example JSON.stringify() and JSON.parse() here: http://www.JSON.org/js.html

Otherwise, I would probably use a coll.


Viewing 4 posts - 1 through 4 (of 4 total)