将JSON对象与键值组合在一起

时间:2017-01-08 21:51:05

标签: javascript json

我有多个JavaScribt对象,我使用JSON.stringify带来了以下格式:

{"date":"2016-01-07T12:45:00.000Z",
 "duration":120,
 "location":"ExampleLocation"}

现在我想将这些对象保存为一个变量,格式如下:

var labs = {
        "2016-01-07":[{
            "date":"2016-01-07T12:45:00.000Z",
            "duration":120,
            "location":"ExampleLocation"
        }],
        "2017-01-05":[{
            "date": "2017-01-05T14:45:00.000Z",
            "duration": 120,
            "location": "ExampleLocation"
        }], //etc
}

所以我想组合对象并将其中一个值绘制为" key"到每个对象。我完全不知道如何实现这一点。

2 个答案:

答案 0 :(得分:0)

你应该遍历对象数组,从index属性创建date,然后你应该检查你的分组数组是否包含这个索引,如果是,你应该将当前元素推送到该索引下的数组,如果不是,你应该在该索引下创建新数组并将当前元素推送到它。

请看下面的代码段。



var elements = [{"date":"2016-01-07T12:45:00.000Z",
                 "duration":120,
                 "location":"ExampleLocation1"},
                {"date":"2016-01-04T12:45:00.000Z",
                 "duration":120,
                 "location":"ExampleLocation2"},
                {"date":"2016-01-05T12:45:00.000Z",
                 "duration":120,
                 "location":"ExampleLocation3"},
                {"date":"2016-01-07T12:45:00.000Z",
                 "duration":120,
                 "location":"ExampleLocation4"},
                {"date":"2016-01-05T12:45:00.000Z",
                 "duration":120,
                 "location":"ExampleLocation5"}];

var groupedElements = {};

elements.forEach(function(element) {

  var index = element.date.slice(0, 10);
  
  if(groupedElements[index] === undefined) {
     groupedElements[index] = [];
  }
  
  groupedElements[index].push(element);
  
});

document.write(JSON.stringify(groupedElements));




答案 1 :(得分:0)

您可以使用reduce按日期创建新对象分组,并将值放在数组中:



var arr = [
  {"date":"2016-01-06T12:15:00.000Z", "duration":120, "location":"ExampleLocation"},
  {"date":"2016-01-06T12:45:00.000Z", "duration":120, "location":"ExampleLocation"},
  {"date":"2017-07-07T12:45:30.000Z", "duration":120, "location":"ExampleLocation"},
  {"date":"2017-07-07T12:45:44.000Z", "duration":120, "location":"ExampleLocation"},
];
  
var grouped = arr.reduce((a, next) => {
  let key = next.date.split('T')[0];
  a[key] = (a[key] || []).concat(next);
  return a;
}, {});

console.log(grouped);