Linda
Linda

Reputation: 2405

Create Random data in my own format

I want to create some random-data in this format

var dataStructure = [
   {
      "data":[
         {
            "itemLabel":"label1",
            "itemValue":0.8
         },
         {
            "itemLabel":"label2",
            "itemValue":0.2
         },
         {
            "itemLabel":"label3",
            "itemValue":0.7
         },
         {
            "itemLabel":"label4",
            "itemValue":0.1
         },
      ],
      "label":"biglabel1"
   },
   {
      "data":[
         {
            "itemLabel":"label1",
            "itemValue":0.5
         },
         {
            "itemLabel":"label2",
            "itemValue":0.9
         },
         {
            "itemLabel":"label3",
            "itemValue":0.1
         },
         {
            "itemLabel":"label4",
            "itemValue":0.3
         },
      ],
      "label":"biglabel1"
   }, ...
]

and i've wrote this code

var item = ["label1", "label2", "label3", "label4", "label5"];
var dataStructure2 = [],
dat = [];
data = {};
object = {};
label = ["biglabel1","biglabel2","biglabel3","biglabel4"];

for (var i=0; i<4; i++){
    for(var j=0; j<4; j++){
        dat.push(data.itemLabel = item[i]);
        dat.push(data.itemValue = Math.random());
    }
    dataStructure2.push(object.data = data, object.label = label[i]);
}

I'm just a little bit confused if this is right...maybe its to late but i hope someone could have a look, because the browser doesn't show the object names.

Upvotes: 0

Views: 36

Answers (1)

Guffa
Guffa

Reputation: 700562

You are using the wrong syntax for pushing an object to an array. A statement like dat.push(data.itemLabel = item[i]); doesn't put an object in the array and set a property of the object. The expression data.itemLabel = item[i] will put the value in the object, but the value of the expression is item[i], so that is what's pushed to the array.

You need to create a new object for each item that you want to push into an array:

var item = ["label1", "label2", "label3", "label4", "label5"];
var dataStructure2 = [], dat, data, object;
var label = ["biglabel1","biglabel2","biglabel3","biglabel4"];

for (var i=0; i<label.length; i++){
  dat = [];
  for(var j=0; j<item.length; j++){
    data = {};
    data.itemLabel = item[i];
    data.itemValue = Math.floor(Math.random() * 10) / 10;
    dat.push(data);
  }
  object = {};
  object.data = dat;
  object.label = label[i];
  dataStructure2.push(object);
}

Alternatively, instead of first creating an object and then set properties, you can use the object literal syntax. Example:

object = {
  data: dat,
  label: label[i]
};

You can actually push the object directly without storing it in a variable first:

dataStructure2.push({
  data: dat,
  label: label[i]
});

Upvotes: 1

Related Questions