如何重构JS对象?

时间:2016-10-17 17:32:27

标签: javascript

我有一个像这样结构的约会列表(取自JSON格式):

var oData = {
    "data": {
        "d": {
            "results": [
                {
                    "Room": "403",
                    "Title": "MaLyssa Scott Meeting",
                    "Category": "Meeting",
                    "EventDate": "2016-10-31T19:30:00Z",
                    "EndDate": "2016-10-31T21:00:00Z"
                },
                {
                    "Room": "403",
                    "Title": "OF Upgrade Meeting",
                    "Category": "Meeting",
                    "EventDate": "2016-10-13T17:00:00Z",
                    "EndDate": "2016-10-13T18:00:00Z"
                },
                {
                    "Room": "428",
                    "Title": "IPAC DTID CRM",
                    "Category": "Meeting",
                    "EventDate": "2016-10-12T17:30:00Z",
                    "EndDate": "2016-10-12T18:30:00Z"
                },
                {
                    "Room": "434",
                    "Title": "BPR-12-001 Updates",
                    "Category": "Meeting",
                    "EventDate": "2016-10-10T15:00:00Z",
                    "EndDate": "2016-10-10T15:30:00Z"
                },
                {
                    "Room": "436",
                    "Title": "OF Update Meeting",
                    "Category": "Work hours",
                    "EventDate": "2016-10-12T17:00:00Z",
                    "EndDate": "2016-10-12T18:00:00Z"
                },
                {
                    "Room": "454",
                    "Title": "Real Property Meeting",
                    "Category": "Meeting",
                    "EventDate": "2016-10-12T20:00:00Z",
                    "EndDate": "2016-10-12T21:00:00Z"
                }
            ]
        }
    }
}      

我需要按房间号对结果数组进行分组,例如,房间403有2个孩子,他们是彼此的兄弟姐妹而不是2个独立的对象。

我想我可以用' if'声明,然后将对象推送到每个房间的数组中,最佳做法是执行类似的操作吗?

1 个答案:

答案 0 :(得分:1)

您可以使用reduce -

var newData = oData.data.d.results.reduce(function(prev,curr){
    if (!prev[curr.Room]) { // if room not already in the object add it.
        prev[curr.Room] = [];
    }
    prev[curr.Room].push(curr); 
    return prev;
}, {}); // init with an empty object

console.log(newData);