foreach javascript array

Asked

Viewed 392 times

3

I have the following script:

var data = JSON.parse( '<?php echo json_encode($lista_tipo_indicadores) ?>' );
  var cores = JSON.parse('<?php echo json_encode($cores) ?>');
  // Quantidade de Indicadores por Tipo
  var doughnutData = [
      {
          value: data[0].total,
          color:cores[0],
          highlight: "#FF5A5E",
         label: data[0].nome
      },
      {
          value: data[1].total,
          color: cores[1],
          highlight: "#5AD3D1",
          label: data[1].nome
      },
      {
          value: data[2].total,
          color: cores[2],
          highlight: "#FFC870",
          label: data[2].nome
      },
      {
          value: data[3].total,
          color: cores[3],
          highlight: "#5AD3D1",
          label: data[3].nome
      },
      {
          value: data[4].total,
          color: cores[4],
          highlight: "#FFC870",
          label: data[4].nome
      },
      {
          value: data[5].total,
          color: cores[5],
          highlight: "#5AD3D1",
          label: data[5].nome
      },
      {
          value: data[6].total,
          color: cores[6],
          highlight: "#FFC870",
          label: data[6].nome
      },
      {
          value: data[7].total,
          color: cores[7],
          highlight: "#FFC870",
          label: data[7].nome
      }
  ];

How do I make the variable to be generated dynamically, with some foreach?

  • Confirm that I understand correctly, you want to fill in the doughnutData variable by foreach instead of having to do it manually?

  • What is the relationship between date and colors and Highlight? Colors come from the I imagine array, but both have the same number of elements?

1 answer

4


If both arrays are the same size, ie length you can iterate one of them and map to include data from the other. It seems more practical to iterate data because they have more content to be used.

So you can do:

// Quantidade de Indicadores por Tipo
var doughnutData = data.map(function(_data, i){
      return {
          value: _data.total,
          color: cores[i],
          label: _data.nome
      };
});

The relationship with the highlight but if this is a third array you can integrate in the same way. An example using Highlight as a starting point would be:

var highlight = ["#FF5A5E", "#5AD3D1", "#FFC870", "#5AD3D1", "#FFC870", "#5AD3D1", "#FFC870", "#FFC870"];
var doughnutData = highlight.map(function(_highlight, i){
      return {
          value: data[i].total,
          color: cores[i],
          highlight: _highlight
          label: data[i].nome
      };
});
  • Ball show your answer Sérgio. The last option worked perfectly. : D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.