To avoid using variable name as a literal, use square brackets. Following is the code −
Example
var name = "David"
var putTheAllData = []
putTheAllData.push( { name: "The name is name will remain same" } )
putTheAllData.push( { [name]: "The name is David will be changed [name]"} )
console.log(putTheAllData);To run the above program, you need to use the following command −
node fileName.js.
Output
Here, my file name is demo166.js. This will produce the following output −
PS C:\Users\Amit\javascript-code> node demo166.js
[
{ name: 'The name is name will remain same' },
{ David: 'The name is David will be changed [name]' }
]