Hi guys I’m trying to create a javascript object like this:
data = { values:[
{ X: "Apples", Y: 120 },
{ X: "Oranges", Y: 280 },
{ X: "Chocolates", Y: 180 },
{ X: "Bananas", Y: 340 },
{ X: "Tomatoes", Y: 400 },
]};
I’ve tried this but it doesn’t work?
var data = {};
for (i = 0; i < json.Answers.length; i++){
data.values[i].X = json.Answers[i].AnswerText
data.values[i].Y = json.Answers[i].Responses.length
}
The json part is fine, any ideas on constructiong the object?
First, you’re trying to use a
valuesproperty ofdatathat you’ve never defined. Changeto
That creates the
valuesarray.Also, in your loop you’re trying to assign to objects that don’t exist. Change the content of the loop to:
That creates each object that goes in the
valuesarray as you build it.So:
(Side note: Don’t forget to declare
i, if it’s not already declared, lest you fall prey to The Horror of Implicit Globals.)