Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
Defining an object key as the value of a given variable and not the name of variable itself

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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

Edit: You can do the same thing with ES6+ as well, as @MikhailSemikolenov pointed out.

let indices = indexSum;
var lossColor = {};

for (let i = 1; i <= indices; i++) {
  lossColor = { ...lossColor, [i]: { color: "red" } }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda