Reputation: 635
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
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));
Upvotes: 4