Fred
Fred

Reputation: 35

How can I use Array as Object key in javascript?

I want to make a dictionary that able to get same result with different keys,
so I did something like this in javascript:

var dictionary = {
        [CHW,CW] : {                      //CHW and CW is ref to same thing
            [FLOW,FLW,FW] : 'Result 1'    //FLOW, FLW and FW is ref to same thing(Flow)
           }
        }

The code above only showing the concept, what I should do to get my expected output below?
expected output:
dictionary.CHW.FLW   //output: 'Result 1'
dictionary.CW.FLW    //output: 'Result 1'
dictionary.CW.FLOW   //output: 'Result 1'
dictionary.ABC.EFG   //output:  undefined

My ultimate goal is to able to get the same output by calling different keys in the dictionary. Is there any library/Logic that can do so? Thanks for helping me out!

Upvotes: 0

Views: 45

Answers (2)

deepak
deepak

Reputation: 1375

you can create computed property in the object. Here I am assuming you are storing key in variable.

var dictionary = {
        [CHW] : {
              [CW]: {
                      [FLOW] : 'Result 1'
                    }
                  }
              }

now you can access the way you want. dictionary[CHW][CW][FLLOW] give you 'Result 1'

Upvotes: 0

mbojko
mbojko

Reputation: 14679

Plain object can't do that, a Map can:

The Map object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Upvotes: 2

Related Questions