Home > Software engineering >  how to set json attribute using const value
how to set json attribute using const value

Time:11-16

I want to make Json attribute using const data like this.

const title = 'NAME'
data = {title: 'This is title'}
console.log(JSON.stringify(data))

I want this result => {NAME: 'This is title'}

but this shown => {title: 'This is title'}

What should I do?

CodePudding user response:

For dynamic key, you can use [variableName] notation.

So change title to [title]

const title = 'NAME'
data = {[title]: 'This is title'}
console.log(JSON.stringify(data))

  •  Tags:  
  • json
  • Related