0

I'm trying to populate an array 'arr' inside the object 'obj' with a property I defined inside this 'obj', in this case, the property 'x';

Basically the array would have x values, but instead, when accessing 'arr', all the entries are undefined.

What I did:

var obj = {
  x: 1,
  arr: [this.x, this.x, this.x],
};

console.log(obj.arr)

How should I refer to x inside the array? I tried enclosing arr with brackets, but that would only give me a syntax error. I tried searching how would this work but have found nothing useful...

Furthermore, I would like that arr to be of two dimensions, such that:

var obj = {
  x: 1,
  arr: [
  [this.x, this.x, this.x],
  [this.x, this.x, this.x],
  [this.x, this.x, this.x]
  ],
 };
 
 
 console.log(obj.arr);

How would it work then?

  • 1
    Does this answer your question? [Self-references in object literals / initializers](https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers) – Munzer Apr 04 '20 at 20:44

4 Answers4

2

You cant refer this in the object, this works with function. To access the property, u can assign and reuse.

Other way around, USING ES6 get to simplify it. But you cant set it back again in that case. It will be read-only.

Check example.

var obj = {
  x: 1
};
obj.arr = [obj.x, obj.x, obj.x]

console.log(obj.arr)

/// Other way arround , USING ES6 get

var obj = {
  x: 1,
  get arr() {
    return [this.x, this.x, this.x];
  },
};
console.log(obj.arr); // [1,1,1]
obj.arr = [1] // modify
console.log(obj.arr); // [1,1,1] still same
.as-console-row {
  color: blue !important;
}
xdeepakv
  • 7,835
  • 2
  • 22
  • 32
0

This is because the user cannot access this to initialize any other property until object is created. If you still wanna create an array, then you can define it as a method whose execution is pending unless called.

var obj = {
  x: 1,
  arr: function() {
    return [this.x, this.x, this.x]
  }
};

console.log(obj.arr())

else you can create an arr property after creating object.

var obj = {
  x: 1,
};
obj['arr'] = [obj.x, obj.x, obj.x];

console.log(obj.arr);
Jasdeep Singh
  • 7,901
  • 1
  • 11
  • 28
0

Generally you can't reference an object during initialisation. You'd have to do it afterwards like this:

var obj = {
  x: 1,
 };

obj.arr = new Array(3).fill(obj.x);

console.log(obj);

However, post ECMAScript 2015 you can do this using getter()

    var obj = {
      x: 1,
      get arr() {
        return [this.x, this.x, this.x];
      }
     };

    console.log(obj);
Paul Ryan
  • 461
  • 2
  • 6
0

There are many solutions that you can see in this topic: Self-references in object literals / initializers

Here some of them:

Solution 1

var obj = {
  x: 1,
  get arr() {
    return [this.x, this.x, this.x]
  }
};

Solution 2

var x = 1;
var obj = {
  x: x,
  arr: [x, x, x]
};

Solution 3

var obj = {
  x: 1,
};

obj.arr = [ obj.x, obj.x, obj.x ];
secon25
  • 70
  • 9