Javascript: multidimensional object

I want to create an object starting with something like:

var map = {}; 

Then I want to add elements using this function:

 add = function(integerA, objectB) { map[objectB.type][integerA] = objectB; } 

So this is a random example of the structure of an object that I want to achieve:

 map = { 'SomeType' : { 0 : 'obj', 2 : 'obj', 3 : 'obj' }, 'OtherType' : { 0 : 'obj', 5 : 'obj' }, }; 

Now, my problem. I can not do map[objectB.type][integerA] = objectB; because map[objectB.type] is undefined. I could solve this by checking if map[objectB.type] through an if-statement and if necessary creates map[objectB.type] = {}; .

Otherwise, I could preload all types of objects. However, I would prefer not to.

My question is: is there a way to create an object on the fly without checking if there is a type that exists every time I want to call the add function or preload all types?

It is important that my add function is as fast as possible, and that the map object is correct, because I need to read and write a lot in a short amount of time (this is an animation / game application).

+8
javascript object multidimensional-array
source share
3 answers

No, there is no other way to create objects on the fly. Check availability only every time:

 add = function(integerA, objectB) { if (!map[objectB.type]) { map[objectB.type] = {}; } map[objectB.type][integerA] = objectB; } 

If you want to improve performance, you can consider some caching technologies.

+9
source share

You can use a logical OR-short link (which avoids at least an explicit if ). Perhaps this is not so clear:

 var data = map[objectB.type] || (map[objectB.type] = {}); data[integerA] = objectB; 

This works because an assignment actually returns the value that was assigned, and the OR expression returns the first value, which evaluates to true .

I don't think that using if has any impact on performance, though (in fact, the method in my answer may even be β€œslower”).

+3
source share

If you use the map only for search, and you do not need to sort out the sizes, you can combine your measurements in one key. For example:

 add = function(integerA, objectB) { var key = objectB.type + '-' + integerA; map[key] = objectB; } 
+3
source share

All Articles