Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you evaluate a property name within a JS object? [duplicate]

Tags:

javascript

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"
};
like image 926
Evan Avatar asked Aug 18 '15 22:08

Evan


1 Answers

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.

like image 87
Pointy Avatar answered Sep 21 '22 04:09

Pointy