简体   繁体   中英

GroupBy using underscore.js using nested JSON object

I am trying to group this JSON by using BroadCategory attribute of category

[{
"brand": "Brand3",
"category": {
    "popularity_index": 7,
    "BroadCategory ": "BroadCategory4",
    "MainCategory": "MainCategory410",
    "GeneralCategory": "GeneralCategory41"
},
"description": "colonialism",
"discount": 17,
"id": 9
}, {
"brand": "Brand2",
"category": {
    "popularity_index": 5,
    "BroadCategory ": "BroadCategory2",
    "MainCategory": "MainCategory210",
    "GeneralCategory": "GeneralCategory21"
},
"description": "desc2",
"discount": 15,
"id": 2
}]

I went through underscore.js - _.groupBy nested attribute but this has array inside JSON for location

I tried something like:

var grpArray = _.groupBy(products, function (element) {
   return element.category.BroadCategory;
})

but its not working. Why can't I access BroadCategory ?

You have to trim a space "BroadCategory "

"BroadCategory ": "BroadCategory2",

Change to:

"BroadCategory": "BroadCategory2",

OR:

_.groupBy(products, function (element) {
   return element.category['BroadCategory '];
})

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