Concatenating Javascript Object

2

I have the following javascript array:

    for(var k in lista) {
            for(var x in lista[k]){
                var donutData = [
                    {label: x, data: lista[k][x], color: "#3c8dbc"}
                ];
            }
        }

In the end I would like the donutData variable to look like this:

    var donutData = [
      {label: "Series2", data: 30, color: "#3c8dbc"},
      {label: "Series3", data: 20, color: "#F56954"},
      {label: "Series4", data: 50, color: "#00A65A"},
      {label: "Series4", data: 50, color: "#F39C12"},
      {label: "Series4", data: 50, color: "#00C0EF"}
    ];

Is it possible?

    
asked by anonymous 06.06.2016 / 22:23

2 answers

3

Your original code is doing the following:

  • Starting a loop, k ;
  • Starting a sub-loop, x ;
  • Initializing a variable of type array, donutData ;
  • Populating donutData with an element via push() method.

Note that for every cycle of k and x , donutData is reset - thus resulting in a variable containing only one element, always.

To solve your problem, reallocate the donutData variable, creating it before you start the loops:

var donutData = [];

for(var k in lista) {
     for(var x in lista[k]){
         donutData.push({label: x, data: lista[k][x], color: "#3c8dbc"});
     }
 }

So the value of donutData will be preserved between iterations of the loops.

    
06.06.2016 / 22:52
2

You should use push to add elements to an array and it's not worth it to always initialize the variable within the loop:

var donutData = [];
for(var k in lista) {
     for(var x in lista[k]){
         donutData.push({label: x, data: lista[k][x], color: "#3c8dbc"});
     }
 }

This starting from the principle that matches your varable list structure. Note that you will not get the result you want, at least in the field of color , which will always be the same. Without seeing lista , I do not know where to go to get the color inside the lista .

    
06.06.2016 / 22:29