foreach javascript array

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 get the variable to be generated dynamically, with some foreach?

    
asked by anonymous 29.01.2016 / 13:59

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 use.

So you can do it:

// 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 highlight is not clear, 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
      };
});
    
29.01.2016 / 14:44