TransWikia.com

How can I use Array as Object key in javascript?

Stack Overflow Asked on November 30, 2020

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!

2 Answers

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

Correct answer by mbojko on November 30, 2020

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'

Answered by deepak on November 30, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP