Can you evaluate the name of a property inside a JS object?

I know that you can evaluate the value of a property inside a JS object, for example:

let object = { value: 5+5 }; 

I am wondering if there is a way to evaluate the attribute name using JS, i.e. achieve the following:

 let object; object[5+5].value = "ten"; 

Something like:

 let object = { 5+5: "ten" }; 
+4
source share
2 answers

Yes in ES2015, no in ES5, but first allow one thing: JavaScript, not JSON.

In ES2015 (formerly known as ES6):

 var something = "foo"; var object = { [something]: "bar"; }; alert(object.foo); // "bar" 

Inside [ ] can be any expression that you like. The return value is coerced to the string. That means you have hours of fun with things like

 var counter = function() { var counter = 1; return function() { return counter++; }; }; var object = { ["property" + counter()]: "first property", ["property" + counter()]: "second property" }; alert(object.property2); // "second property" 

JSON is a serialization format based on the syntax of a JavaScript object initializer. There is no way in JSON to do anything like this.

+5
source

Sure. Try the following:

 'use strict'; let object = { [5+5]: "ten" }; console.log(object); // Object {10: "ten"} 
+1
source

All Articles