NoSQLZoo

JavaScript: Computed Properties

In the JavaScript: Fundamentals tutorial we briefly looked at creating and using objects. Occasionally we may want to create objects and properties 'dynamically', i.e. objects created "on-the-fly" instead of hard-coded into our applications.

Take the following example. We have a collection of people objects with names and ages, e.g.

{
  name: "Bob",
  age: 50
}

and for each person we want to create an object with the following structure:

{
  Bob: 50
}

We might try to do something like the following:

let people = [{
  name: "Bob",
  age: 50
}, {
  name: "Alice",
  age: 52
}];
for (let index = 0; index < people.length; index++) {
  let person = people[index];
  let output = {
    person.name: person.age
  };
  print(JSON.stringify(output));
}

Unfortunately, as you can see in the editor above, this approach creates errors. To get around these errors we can use a JavaScript feature known as Computed Property Names. Using this is simple: put square brackets ([, ]) around any field that needs to be computed. In the above example, person.name: person.age becomes [person.name]: person.age.

let people = [{
  name: "Bob",
  age: 50
}, {
  name: "Alice",
  age: 52
}];
for (let index = 0; index < people.length; index++) {
  let person = people[index];
  let output = {
    [person.name]: person.age
  };
  print(JSON.stringify(output));
}

Another way of doing this is to split the property initialisation from the object initialisation.

let people = [{
  name: "Bob",
  age: 50
}, {
  name: "Alice",
  age: 52
}];
for (let index = 0; index < people.length; index++) {
  let person = people[index];
  let output = {};
  output[person.name] = person.age;
  print(JSON.stringify(output));
}