Cookies help us deliver our services. By using our services, you agree to our use of cookies. More information

JavaScript: Computed Properties

From NoSQLZoo
Revision as of 14:38, 17 October 2018 by 40166222 (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

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, simply put square brackets ([, ]) around any field that needs to be computed.
In the above example, person.name: person.age</code> becomes <syntaxhighlight lang="JavaScript" inline>[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));
}