将数据推送到复杂的JSON对象

时间:2017-03-03 13:00:03

标签: arrays json

我想创建一个json对象,其最终结构应如下所示:

crossdata = {
     "reports" : {
                   {"name" : "emp1", "age" : "20", "height" : "180"},
                   {"name" : "emp2", "age" : "33", "height" : "185"},
                   {"name" : "emp3", "age" : "31", "height" : "176"}
                   {"name" : "emp4", "age" : "42", "height" : "188"}
                 },
     "process" : {
                   {"time" : "260", "opt" : "1", "area" : "north", "active" : "1"},
                   {"time" : "123", "opt" : "0", "area" : "north", "active" : "1"},
                 },
     "status" : {
                   {"actual" : "1", "sync" : "1"},
                   {"actual" : "1", "sync" : "0"},
                   {"actual" : "0", "sync" : "0"},
                 }
        }

正如您所看到的,交叉数据中的三个对象(或者它们是数组?)可能具有不同数量的"记录",从IndexedDB收集数据。

所以,在顶线我声明:

crossdata = { "reports" : {}, "process" : {}, "status" : {} };

然后我试图将重复循环中从DB收集的数据推送到:

      //some DB code (reports table) // (function(r){
        for (i=0; i<r.length; i++){
          crossdata.reports.push ({
            "name" : r[i].name, "age" : r[i].age, "height" : r[i].height
          });
        }
      });
      //some DB code (process table) // (function(r){
        for (i=0; i<r.length; i++){
          crossdata.process.push ({
            "time" : r[i].time, "opt" : r[i].opt, "area" : r[i].area, "active" : r[i].active
          });
        }
      });
      //some DB code (status table) // (function(r){
        for (i=0; i<r.length; i++){
          crossdata.status.push ({
            "actual" : r[i].actual, "sync" : r[i].sync
          });
        }
      });

但是,它不起作用,我一直收到错误,表明crossdata.reports.push不是函数。我想这与数组与对象,方括号和解析有关,但应用类似讨论的解决方案并不适合我。

关于如何实现这种结构的任何想法?

谢谢!

1 个答案:

答案 0 :(得分:0)

使用

crossdata = { "reports" : [], "process" : [], "status" : [] };

声明数组。您在那里声明了没有本地push()方法的对象。

{}是一个对象文字,而[]是一个数组文字。如果你想使用像push()这样的数组函数,你显然必须声明数组。

相关问题