0

I have a few variables which are defined as:

function test() {
  var foo = 'bar'
  var dict = {
    foo: 'haha'
  }
  Logger.log(dict['foo'])  // haha
  Logger.log(dict[foo])    // undefined. I expected this to return 'haha'. But I was wrong.
}

Is it possible to create a dictionary that contains bar as its key using the variable foo?

I mean I want to get 'haha' by using the variable foo.

Brian
  • 12,145
  • 20
  • 90
  • 153
  • I have a question for understanding your question. In your script, ``dict[foo]`` and ``dict['bar']`` are the same. I thought that if you want to retrieve ``'haha'`` from both, it can be achieved by putting ``dict[foo] = 'haha'`` after ``var dict = {foo: 'haha'}``. But you want to retrieve ``'haha'`` from both ``dict[foo]`` and ``dict['bar']`` without adding the property. Is my understanding correct? – Tanaike Jul 17 '18 at 08:02
  • I want to retrieve `haha` from the variable `foo`. I will delete `Logger.log(dict['bar'])` so that you don't get confused. – Brian Jul 17 '18 at 08:29
  • Thank you for your reply. I'm sorry if I still don't understand your question. For example, I thought that what you want might be like ``for (foo in dict) Logger.log(dict[foo])``. But you want to retrieve ``'haha'`` without both overwriting ``foo`` and adding some properties to ``dict``. Is my understanding correct? – Tanaike Jul 17 '18 at 08:45
  • 3
    Your code should work if you change `dict` init to: var dict = {}; dict[foo] = 'haha'; See https://stackoverflow.com/a/6500664 – Kos Jul 17 '18 at 09:04

1 Answers1

0
function test() {
  var foo = 'bar'
  var dict = {
    foo: 'haha',
    sec: foo
  }
  Logger.log(dict['foo'])  // haha
  Logger.log(dict[foo])    // undefined
  Logger.log(dict['bar'])  // undefined
  Logger.log(dict['sec'])  // bar - gets the variable foo
 }
kris
  • 392
  • 4
  • 16