Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting string from variable (from imported JS) as key in object

How can I make a variable the key to an object?

I am importing constants from definitions.js and these constants I need to use as keys:

import * as cons from '../scripts/definitions.js'

export default {
  data () {
    return {
      cons: cons,
      obj: {
        cons.FILENAMEA: {},
        cons.FILENAMEB: {
          children: [
            cons.CHILDFILENAME1,
            cons.CHILDFILENAME2,
            cons.CHILDFILENAME3
          ]
        }
      }
    }
  },

With above codes, I am getting error:

Parsing error: Unexpected token, expected ","

Because of the dot (.) in cons.FILENAMEA. How to do this?? Please note that I need to get these variables/constants from an external file. Not possible to just declare it on the same file.

Thanks!

like image 820
kzaiwo Avatar asked Dec 18 '25 19:12

kzaiwo


1 Answers

You can use es6 computed properties:

obj: {
  [cons.FILENAMEA]: {},
  [cons.FILENAMEB]: {
    children: [
      cons.CHILDFILENAME1,
      cons.CHILDFILENAME2,
      cons.CHILDFILENAME3
    ]
  }
}

The expression inside the brackets will be evaluated and used as the property name

like image 72
Dan Avatar answered Dec 20 '25 12:12

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!