简体   繁体   中英

underscore js groupby array inside JSON

I have assigned a task to group data in angular js using underscore js.

My 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"
                    }
                ]
            }
        ]
    }
}

I'm unable to group data using "name" field using underscore js. I tried :

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

But it fails. Need help. Thanks in advance.

Here is my solution for your problem :

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

See it working for your situation : JsFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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