Concatenating Javascript Object

Asked

Viewed 875 times

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"}
                ];
            }
        }

At 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"}
    ];

It is possible?

  • 2

    Without Saver the structure of lista it’s hard to help. Test like this: https://jsfiddle.net/cw890hwc/ if it doesn’t work it puts the structure of lista in the question.

2 answers

3


Your original code is doing the following:

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

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, highlight the donutData variable, creating it before starting 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"});
     }
 }

Thus the value of donutData will be preserved between iterations of ties.

2

Must use push to add elements to an array and it is not worth always initializing the variable within the cycle:

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 its structure of the variable list. Note that you will not get the result you want, at least in the field of color, that always goes the same. Without seeing the lista, I don’t know where to get the color inside the lista.

Browser other questions tagged

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