1

We can write an object in JavaScript as

obj1 = {1:2,2:2,3:10}

However is there a way to write an object with some sort of "MultiDimensional Key" as

obj2= {(1, 1): 1, (1, 2): 1, (1, 3): 1, (1, 4): 1, (1, 5): 1}

If not, what could be an easy way of writing such an object???

Shaurya Gupta
  • 327
  • 3
  • 14
  • 2
    Could you make the key "1-1", "1-2", "2-1", etc? That would be a string value but it might work easily enough – drew_w Dec 26 '13 at 15:29
  • possible duplicate of [JavaScript Hashmap Equivalent](http://stackoverflow.com/questions/368280/javascript-hashmap-equivalent) – Joseph Dec 26 '13 at 15:30
  • @drew_w I'd prefer numeric values, although the way you have suggested is quite good. – Shaurya Gupta Dec 26 '13 at 15:30
  • This kind of problems are addressed by maps in the world of collections, but since JS is for retarded in this matter - how could you possibly learn about it. Take a look at Java or C# collections libraries and learn them and your life will become a lot more predictable and logical. – luke1985 Dec 26 '13 at 16:32

3 Answers3

2

Yes, you can achieve this, but without objects.

You can use ES6 WeakMap:

WeakMaps are key/value maps in which keys are objects.

Or you could also use Map:

Map objects are simple key/value maps. Any value (both objects and primitive values) may be used as either a key or a value.

Be aware that neither is widely supported, but you can use ES6 Shim (requires native ES5 or ES5 Shim) to support Map, but not WeakMap (see why).

Oriol
  • 274,082
  • 63
  • 437
  • 513
2

You can simulate it like this :

obj2 = {
    1: {
        1: 1,
        2: 1,
        3: 1,
        4: 1,
        5: 1
    }
}

That's easy to read (for example, to refer to index (1, 3), just do obj2[1][3]), but not easy to write (you have to check the existence of the 2nd level key every time).

Sebastien C.
  • 4,649
  • 1
  • 21
  • 32
0

No.

Javascript objects only have string keys.

You could convert your tuples into strings.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964