使用多个数组创建json对象

时间:2017-04-27 20:38:38

标签: jquery

我正在尝试创建一个SINGLE数据obj以发送到API,但是我需要使用多个数组构建json obj。以下代码将正确记录信息,但在创建数据时,obj仅使用第一次迭代。有谁知道如何为我的数组的每个计数打印数据?

 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];
                };

期望的输出

 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];
  }

1 个答案:

答案 0 :(得分:2)

你不能在同一级别拥有相同的密钥,密钥是&#34; theColor&#34;,&#34; theShape&#34; ...

所以你需要有这样的结构

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

所以你可以对它进行循环并访问其中任何一个,这是一个生成该结构的工作示例

 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