user2168066
user2168066

Reputation: 635

Creating json object using multiple arrays

I am trying to create a SINGLE data obj to send to an API, however I need to build the json obj using multiple arrays. The below code will log the information correctly, but when creating the data obj only uses the first iteration. Does anyone know how i could have the data print for each count of my array?

 var quantity = [1, 2, 3];
 var color    = ['blue', 'red', 'green'];
 var shape    = ['square', 'rectangle', 'circle'];

 //note, the arrays will always be the same length

 var len = quantity.length;

 for (var x = 0; x < len; x++) {
     var data = {
                 "theQuantity" : quantity[x];
                 "theColor"    : color[x];
                 "theShape"    : shape[x];
                };

desired output

 data = {
                 "theQuantity" = quantity[x];
                 "theColor"    = color[x];
                 "theShape"    = shape[x];
                 "theQuantity" = quantity[x];
                 "theColor"    = color[x];
                 "theShape"    = shape[x];
                 "theQuantity" = quantity[x];
                 "theColor"    = color[x];
                 "theShape"    = shape[x];
  }

Upvotes: 1

Views: 4012

Answers (1)

xploshioOn
xploshioOn

Reputation: 4125

You can't have the same key on the same level, the key is "theColor", "theShape"...

So you need to have an structure like this

[
    {
        "theQuantity": 1,
        "theColor": "blue",
        "theShape": "square"
    },
    {
        "theQuantity": 2,
        "theColor": "red",
        "theShape": "rectangle"
    },
    {
        "theQuantity": 3,
        "theColor": "green",
        "theShape": "circle"
    }
]

so you then can make a loop on this and access to any of them, here is a working example that generate that structure

 var quantity = [1, 2, 3];
 var color    = ['blue', 'red', 'green'];
 var shape    = ['square', 'rectangle', 'circle'];

 //note, the arrays will always be the same length

 var len = quantity.length;
 var data = []
 for (var x = 0; x < len; x++) {
   var element = {
                 "theQuantity" : quantity[x],
                 "theColor"    : color[x],
                 "theShape"    : shape[x]
   };
   data.push(element);
 }
console.log(JSON.stringify(data));

working example

Upvotes: 4

Related Questions