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???

4
  • 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 Commented Dec 26, 2013 at 15:29
  • possible duplicate of JavaScript Hashmap Equivalent Commented Dec 26, 2013 at 15:30
  • @drew_w I'd prefer numeric values, although the way you have suggested is quite good. Commented Dec 26, 2013 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. Commented Dec 26, 2013 at 16:32

3 Answers 3

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).

Sign up to request clarification or add additional context in comments.

Comments

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).

Comments

0

No.

Javascript objects only have string keys.

You could convert your tuples into strings.

2 Comments

"Javascript objects only have string keys". The obj1 that I have written works correctly.
@shauryagupta Because numbers are coerced into strings

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.