5

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

let object = {
  value: 5+5
};

I am wondering if there is any possible way to evaluate the name of an attribute with JS, i.e. achieve the following:

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

As something like:

let object = {
  5+5: "ten"
};
JAAulde
  • 19,250
  • 5
  • 52
  • 63
Evan
  • 75
  • 3
  • 3
    There is no JSON in your code. JSON stands for "JavaScript Object Notation" and is a String. You just have regular Object literals. – blex Aug 18 '15 at 22:06

2 Answers2

6

Yes in ES2015, no in ES5, but first let's clear one thing up: that's JavaScript, not JSON.

In ES2015 (formerly known as ES6):

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

Inside the [ ] can be any expression you like. The value returned is coerced to a string. That means you can have hours of fun with stuff 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 inspired by JavaScript object initializer syntax. There is definitely no way to do anything like that in JSON.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

Sure. Try this:

'use strict';


let object = {
  [5+5]: "ten"
};

console.log(object); // Object {10: "ten"}
GPicazo
  • 6,516
  • 3
  • 21
  • 24