-1

I want to pass a key name to a dictionary but I am unable to do so. For instance,

let x=[]
let key_names=['a.b.c','g.h.i'] //these can be any values which is a result of another computation
x.push({key_names[0]:1,key_names[1]:2})
console.log(x)
//Expected output - [{'a.b.c':1,'g.h.i':2}]

But this gives me an error -

SyntaxError: Unexpected token [
    at Module._compile (internal/modules/cjs/loader.js:723:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
    at Module.load (internal/modules/cjs/loader.js:653:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
    at Function.Module._load (internal/modules/cjs/loader.js:585:3)
    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
    at startup (internal/bootstrap/node.js:283:19)
    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)

How do I achieve the expected output?

potterson11
  • 147
  • 7

1 Answers1

-1

For computed property, you should wrap it in a bracket []

let x=[]
let key_names=['a.b.c','g.h.i'] //these can be any values which is a result of another computation
x.push({[key_names[0]]:1, [key_names[1]]:2})
console.log(x)

References

Object initializer

hgb123
  • 13,869
  • 3
  • 20
  • 38