-2

I would like to initialize property of object using another property of the same object which is just created using object literal:

var result = {
    a : 1,
    b : a
};

The result should be

{
    a:1,
    b:1
}

Is there any way to do this without first creating object? Using some kind of this?

  • What is your expected behaviour for `result.a++; console.log(result.b)` - outputting `1` or `2`? – connexo Mar 08 '18 at 16:43
  • 1
    Or in other words, do you want `result.b` to have a ***reference*** on `result.a`, or just the initial ***value*** from `result.a`? – connexo Mar 08 '18 at 16:49

4 Answers4

0

You can do that through a function

var result = {
  a: 1,
  getResult: function() {
    return {
      a: 1,
      b: this.a
    }
  }
};
console.log(result.getResult())
brk
  • 48,835
  • 10
  • 56
  • 78
0

You can have a getter for a specific property using Object.defineProperty.

var myObject = {};

Object.defineProperty(
  myObject,
  "b", {
    get: function() {
      return this.a
    }
  }
);


myObject.a = 1;

console.log(myObject.b)
void
  • 36,090
  • 8
  • 62
  • 107
  • ["The fundamental goal of closing duplicate questions is to help people find the right answer by getting **all of those answers in one place**."](https://stackoverflow.com/help/duplicates) – str Mar 08 '18 at 09:56
  • Thank you but I wanted literal solution not dynamic. Good to know about custom getters. – questionair Mar 08 '18 at 12:53
0

You could store the property first in a variable.

var x=1;
var result = {
    a : x,
    b : x
};
console.log(result);
Sascha
  • 4,576
  • 3
  • 13
  • 34
0

Option 1: Use a function instead of an object literal, allowing for this:

let result = function() {
    this.a = 1,
    this.b = this.a;
};

let res = new result()

console.log(res.b)

Option B: Use a custom getter:

var result = {
    a: 1,
    get b() {
      return this.a
    }
};

console.log(result.b); // 1

result.a++;
console.log(result.b); // 2
connexo
  • 53,704
  • 14
  • 91
  • 128