How to dynamically assign the name of a key in an object?

const key = 'name'
const tempObj = {key: 'shiyuq'}
console.log(tempObj)
// {key: 'shiyuq'}
// but I want a object like this  {name: 'shiyuq'}

Finally I find a new way to modify object’s key value,code follows like this:

const tempObj = {[key]: 'shiyuq'}
console.log(tempObj)

I want to know why this can work and what does [ ] mean in this situation? thanks!

103 thoughts on “How to dynamically assign the name of a key in an object?”