Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  12] [ 6]  / answers: 1 / hits: 100984  / 15 Years ago, tue, may 19, 2009, 12:00:00

I have code like this.



var key = anything;   
var object = {
key: key attribute
};


I want to know if there is a way to replace that key with anything.



like



var object = {  
anything: key attribute
};

More From » javascript

 Answers
122

In ES6, use computed property names.



const key = anything;   

const object = {
[key]: key attribute
// ^^^^^ COMPUTED PROPERTY NAME
};


Note the square brackets around key. You can actually specify any expression in the square brackets, not just a variable.


[#99503] Thursday, May 14, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hakeemabramh

Total Points: 234
Total Questions: 109
Total Answers: 109

Location: Romania
Member since Mon, Jun 6, 2022
2 Years ago
;