-1

I want to create an array dynamically which should be having a value in the format of

var dat1 = [
    { x: 0, y: 32.07  },
    { x: 1, y: 37.69  },
    { x: 2, y: 529.49 },
    { x: 3, y: 125.49 },
    { x: 4, y: 59.04  }
];

I want to store the whole thing in data into an array dynamically. I am getting these values from the json data. And I want an array to be in this format. How can I create it?

I tried this:

$.each(r_data, function(key, val) {
    data1.push([{
        x : i,
        y : parseFloat(val.something)
    }]);
    i++;        
});

...but didn't get the result I wanted.

Ash
  • 239
  • 2
  • 9
  • 25

2 Answers2

2

Assuming you have

var data1 = [];

...and probably

var i = 0;

...prior to your code, your code will produce this structure:

var data1 = [
    [ { x: 0, y: 32.07  } ],
    [ { x: 1, y: 37.69  } ],
    [ { x: 2, y: 529.49 } ],
    [ { x: 3, y: 125.49 } ],
    [ { x: 4, y: 59.04  } ]
];

Note how you've ended up with an array where each entry is another array, which in turn contains the object with the x and y properties.

I suspect you want:

var data1 = [];
var i = 0;
$.each(resultBar_data, function(key, value) {
    data1.push({
        x : i,
        y : parseFloat(value.averagePrice)
    });
    i++;        
});

...which just pushes the objects directly on data1, without wrapping them in extra arrays (note I've removed the [] around what's being pushed). You would access those entries like this:

console.log("The first entry is "  + data1[0].x + "," + data1[0].y);
console.log("The second entry is " + data1[1].x + "," + data1[1].y);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

format is an array of objects. In your following code, you are trying to push an array [{x:i, y:parseFloat(value.averagePrice)}] to the format array:

$.each(resultBar_data, function(key, value) {
    format.push([{ /*array start*/
        x : i,
        y : parseFloat(value.averagePrice)
    }] /*array end*/
    );
    i++;        
    });

Remember square brackets denote an array.

I think to fix your problem it should be:

/*i just removed the square brackets so that push now pushes an object, 
not an array with a single object*/
format.push({ 
        x : i,
        y : parseFloat(value.averagePrice)
    });

Hope this helps, please ask if you need more information or if I misunderstood your question!

Lzh
  • 3,585
  • 1
  • 22
  • 36