2

Suppose that I have an object like this (it's a chart js setting).


const radarChartData = {
  labels: [3, 4, 6, 7, 8, 8],
  data: [0, 0, 0, 0, 0, 0],
  bgArr: this.labels.map((label, i) => label === 10 ? "red" : "blue"); // An error has occurred, because this code can't access its own labels in radarChartData.
  datasets: [{.....}]
}

const radarChartConfig = {
  type: ....,
}

const radarChart = new Chart(radarChartCtx, radarChartConfig)

I tried the following fix, but all failed...

bgArr: radarChartData.labels.map((label, i) => label === 10 ? "red" : "blue");

How to access its own property? In the first place, it's not a good option to access it and this way?

Rin
  • 41
  • 5
  • https://stackoverflow.com/questions/4616202/self-references-in-object-literals-initializers?lq=1 – Balaji Nov 05 '21 at 05:55

1 Answers1

2

You can't reference an object during initialization when using object literal syntax. You need to reference the object after it is created. Only way to reference an object during initialization is when you use a constructor function.

This example uses an anonymous function as a constructor. The new object is reference with this

const data = new (function () {
  (this.labels = [3, 4, 6, 7, 8, 8]),
    (this.data = [0, 0, 0, 0, 0, 0]),
    (this.bgArr = this.labels.map((label, i) =>
      label === 10 ? "red" : "blue"
    ));
})();

const radarChartData = {
  labels: data.labels,
  data: data.data,
  bgArr: data.labels.map((label, i) => (label === 10 ? "red" : "blue")),
};

console.log(radarChartData);

/**
 * LOGS
 * { 
 * labels: [ 3, 4, 6, 7, 8, 8 ],
 * data: [ 0, 0, 0, 0, 0, 0 ],
 * bgArr: [ 'blue', 'blue', 'blue', 'blue', 'blue', 'blue' ] 
 * }
 */

Voxelli
  • 126
  • 4