在JSON中强调js groupby数组

时间:2016-06-17 09:56:17

标签: javascript angularjs json

我已经分配了一个任务,使用下划线js对角度js中的数据进行分组。

我的JSON:

$scope.myData= {
"buslist":
    {
        "code":"1",
        "message":"Success",
        "fromStationCode":"71",
        "searchResult": [
            {
                "arrivalTime": "17:00:00",
                "availableSeats": "42",
                "boardingPointDetails": [
                    {
                        "code": "1631",
                        "name": "Koyambedu",
                        "time": "09:30:00"
                    },
                    {
                        "code": "961296",
                        "name": "Nerkundram",
                        "time": "09:45:00"
                    }
                ]
            },
            {
                "arrivalTime": "18:00:00",
                "availableSeats": "32",
                "boardingPointDetails": [
                    {
                        "code": "2084",
                        "name": "Adyar",
                        "time": "09:30:00"
                    },
                    {
                        "code": "961296",
                        "name": "Madurai",
                        "time": "09:45:00"
                    }
                ]
            }
        ]
    }
}

我无法使用" name"使用下划线js的字段。   我试过了:

$scope.groups = _.groupBy($scope.myData,function(element) {
    return element.searchResult.boardingPointDetails.name;
});

但它失败了。需要帮忙。提前谢谢。

1 个答案:

答案 0 :(得分:2)

以下是我的问题解决方案:

var tempResult = [];
_.each($scope.myData.buslist.searchResult, function(result) {
    _.each(result.boardingPointDetails, function(detail) {
        var item = { name: detail.name, availableSeats: result.availableSeats };
        tempResult.push(item); // make an array of items with needed data on same nesting level
    });
});

var endResult = _.groupBy(tempResult, 'name');  // group the items by name

根据您的情况查看它:JsFiddle