简体   繁体   English

将 JSON 对象与键值组合

[英]Combine JSON Objects with Key Value

I have multiple JavaScribt Objects that I bring to following format with JSON.stringify :我有多个 JavaScrit 对象,我使用JSON.stringify将它们转换为以下格式:

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

Now I would like to save these Objects into one Variable with the following format:现在我想用以下格式将这些对象保存到一个变量中:

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
}

So I want to combine the Objects and draw one of the values as "key" to each object.所以我想组合对象并将其中一个值绘制为每个对象的“键”。 I have absolutely no idea how to achieve this.我完全不知道如何实现这一目标。

You should loop through objects array, create index from date property, then you should check if your grouped array contains this index, if yes, you should push current element to array under that index, if not you should create new array under that index and push current element to it.你应该遍历对象数组,从date属性创建index ,然后你应该检查你的分组数组是否包含这个索引,如果是,你应该将当前元素推送到该索引下的数组,如果没有你应该在该索引下创建新数组和将当前元素推送到它。

Take a look on snippet below.看看下面的片段。

 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));

You can use reduce to create a new object grouping by date and putting the values in an array inside:您可以使用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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM