In Javascript collection, use value from earlier key/value in a later value

javascript

Solution

First way, using a property `getter`.

Please note `c` is a property as `b` and `c`.

var collection = {
  a: 1,
  b: 2,
  get c() {
    return this.a + this.b;
  }
};

console.log(collection.a); // 1
console.log(collection.b); // 2
console.log(collection.c); // 3

Second way, using concise method in ES6 or a more "classical" function declaration in ES5.

Please note `c` is now a function.

let collection = {
  a: 1,
  b: 2,
  c() {
    return this.a + this.b;
  }
};

console.log(collection.a); // 1
console.log(collection.b); // 2
console.log(collection.c()); // 3 called as a function

Third way, using a dedicated function for initialization.

This is useful if you have a more complex initialization, maybe on more properties, and could work similarly as a "constructor".

var collection = {
  a: 1,
  b: 2,
  c: 3,
  init: function() {
    this.c = this.a + this.b;
  }
};
collection.init();
console.log(collection.a); // 1
console.log(collection.b); // 2
console.log(collection.c); // 3

Forth way, directly on `c` property.

var collection = {
  a: 1,
  b: 2,
  c: undefined
};
collection.c = collection.a + collection.b;
console.log(collection.a); // 1
console.log(collection.b); // 2
console.log(collection.c); // 3

Regarding specifically your question, I would solve it using a `getter` and appending value "3" in front of `b` (please note result is of type string), example:

var collection = {
  a: 1,
  b: 2,
  get c() {
    return '3' + this.b;
  }
};
console.log(collection.a); //1
console.log(collection.b); //2
console.log(collection.c); //"32"
console.log(typeof collection.c); // string

Problem

I know this sounds silly, but now my curiosity has me stuck on this idea. Is it possible to declare a collection of key/value pairs, like var `collection = {a:"1", b:"2"}` and then have a third pair saying `c: "3" + b.value?`

Original source

Related problems