Home > Enterprise >  Defining an object key as the value of a given variable and not the name of variable itself
Defining an object key as the value of a given variable and not the name of variable itself

Time:10-20

Context: I'm using google charts to create a pie chart and I want to make the last index fixed to color red. To do this, I'm saving a variable as indices that will essentially update the value with the latest index added. I'm then passing to a variable i to become the key of an object that will define the color, but it seems as if google charts doesn't register the variable i and only accepts the numbers from 0,1,2,3,etc.

let indices = indexSum;
for (let i = 1; i <= indices; i  ) {
  var lossColor = {
    i: { color: "red" },
  };
}

In the object that is being saved as lossColor, it will work if I use the number 1 for example as the key, but it won't work if I use i. I'm doing this to keep track of the amount of indices created by the user so that the last index will always be colored red.

var data = new google.visualization.DataTable();
  data.addColumn("string", "Ativo");
  data.addColumn("number", "Quota");
  data.addRows([
    ...slices.map((slice) => [slice.ativo, slice.quota]),
    ["Loss", perda],
  ]);
  //Styling
  let options = {
    legend: "right",
    pieHole: 0.5,
    legend: { textStyle: { color: "gray" } },
    pieSliceText: "value",
    slices: lossColor,
    colors: ["#728FCE", "#FBB117", "#6AA121", "#4863A0", "#7D0552", "#FF0000"],
    backgroundColor: "#22252a",
    chartArea: {
      left: 50,
      right: 50,
      top: 70,
    },
    width: "100%",
    height: "500px",
  };

  var chart = new google.visualization.PieChart(
    document.getElementById("piechart")
  );

  chart.draw(data, options);
}

Is there a way so that the key of the object lossColor retrieves the number itself and not just i as this doesn't seem to be accepted by google charts (there is no error being thrown, it just simply doesn't register the color).

It should appear the number "1" or "2" instead of "i", for example

CodePudding user response:

Well, i: { color: "red" } is basically creating an object with a key called i. To create an object with a key of the value of i, you can firstly initialise an empty object - let myObj = {};, then set the property like so - myObj[i] = "red";.

Here is the updated code:

let indices = indexSum;
var lossColor = {};

for (let i = 1; i <= indices; i  ) {
  lossColor[i] = { color: "red" };
}

Also, use lossColor as a constant, i.e. outside the loop, so that it isn't emptied every time it is looped over.

CodePudding user response:

If you're trying to set the lossColor key to be the value of i, you can't do it the way you're showing. According to MDN - Object Documentation you have to do the following, to create a key with the value of a variable:

let lossColor[i] = { color: "red" }

By the way you're doing, you will create an object with the key i and not with the value of i

  • Related