0
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!

Braiam
  • 1
  • 11
  • 47
  • 78
shiyuq
  • 1
  • 3
  • Does this answer your question? [JavaScript set object key by variable](https://stackoverflow.com/questions/11508463/javascript-set-object-key-by-variable) – eol Jul 03 '20 at 09:03

2 Answers2

2

Computed property names

Starting with ECMAScript 2015, the object initializer syntax also supports computed property names. That allows you to put an expression in brackets [], that will be computed and used as the property name. This is reminiscent of the bracket notation of the property accessor syntax, which you may have used to read and set properties already.

Now you can use a similar syntax in object literals, too:

// Computed property names (ES2015)
let i = 0
let a = {
  ['foo' + ++i]: i,
  ['foo' + ++i]: i,
  ['foo' + ++i]: i
}

console.log(a.foo1) // 1
console.log(a.foo2) // 2
console.log(a.foo3) // 3

let param = 'size'
let config = {
  [param]: 12,
  ['mobile' + param.charAt(0).toUpperCase() + param.slice(1)]: 4
}

console.log(config) // {size: 12, mobileSize: 4}

Copy&Paste from -> Object initializer - JavaScript | MDN

Andreas
  • 21,535
  • 7
  • 47
  • 56
0

Great. Hope you're clear with the use of [ ] notation. But to work in a real-time scenario, Where we get a large set of data in a dynamic format of objects not a single key at a time.

I have created a code-snippet that basically extends your answer in a more advanced manner with sets of objects data in place.

Example:-

Step-1: Let's create a key's object i.e, keysObj

Step-2: Let's create a temp object i.e, tempObj

Step-3: Finally create the variable function i.e, mainObj

const keysObj = {key1: "firstName", key2: "lastName"}; 

const tempObj = {key1: "Naheed", key2: "Shareef"};

const mainObj = Object.keys(tempObj).reduce((obj,k) => Object.assign(obj, { [keysObj[k]]: tempObj[k]  }),{});

console.log(mainObj);

URL: https://es6console.com/kc652vic/

Naheed Shareef
  • 1,011
  • 7
  • 5