从其他数组构造多维数组

时间:2015-12-28 17:20:37

标签: javascript angularjs

我正在使用外部服务来提取组织的事件(GetEvents)。返回的示例:

{
   "Result":"success",
   "Key":"12345",
   "Data":[
     {"ID":"GFDCV34","lastChangedDate":"2015-12-03 11:14:27"},
     {"ID":"IDJHE23","lastChangedDate":"2015-12-03 15:17:47"},
     {"ID":"KDJBD34","lastChangedDate":"2015-12-03 05:25:11"}
   ]
}

接下来,我可以提取某个事件的详细信息(GetEventDetails)。需要事件的ID作为数据参数。我创建了一个返回详细信息的函数getdetails(id);。 例如,对于getdetails('KDJBD34'),它会给我:

{
  "Result":"success",
  "Key":"52523",
  "Data":[
    {
      "ID": "KDJBD34",
      "name": "Name of event 3",
      "date": "date of event 3",
      "location": "location of event 3",
      "lastChangedDate":"2015-12-03 05:25:11"
     }
   ]
}

我想构建一个包含所有事件及其详细信息的数组,如下所示:

{
  "Result": "success",
  "Key": "12345",
  "Data":[
    {
     "ID": "GFDCV34",
     "name": "Name of event 1",
     "date": "date of event 1",
     "location": "location of event 1",
     "lastChangedDate": "2015-12-03 11:14:27"
    },
    {
      "ID": "IDJHE23",
      "name": "Name of event 2",
      "date": "date of event 2",
      "location": "location of event 2",
      "lastChangedDate": "2015-12-03 15:17:47"
    },
    {
      "ID": "KDJBD34",
      "name": "Name of event 3",
      "date": "date of event 3",
      "location": "location of event 3",
      "lastChangedDate":"2015-12-03 05:25:11"
    }
  ]
}

任何可以指引我朝正确方向前进的人?

1 个答案:

答案 0 :(得分:1)

您应该操作第一个结果并附加新检索的属性

var res = {
  "Result": "success",
  "Key": "12345",
  "Data": [{
    "ID": "GFDCV34",
    "lastChangedDate": "2015-12-03 11:14:27"
  }, {
    "ID": "IDJHE23",
    "lastChangedDate": "2015-12-03 15:17:47"
  }, {
    "ID": "KDJBD34",
    "lastChangedDate": "2015-12-03 05:25:11"
  }]
};

var tmp;
res.Data.map(function(val,i){
    tmp = getdetails(val.ID);
    Object.keys(tmp.Data[0]).map(function(v,j){
    val[v] = tmp.Data[0][v];
  });

});

Demo