GroupBy使用嵌套的JSON对象使用underscore.js

时间:2016-01-11 15:49:39

标签: javascript json underscore.js

我正在尝试使用BroadCategory

category属性对此JSON进行分组
[{
"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
}]

我浏览了underscore.js - _.groupBy nested attribute,但这里面有location

的JSON数组

我尝试过类似的事情:

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

但它不起作用。为什么我无法访问BroadCategory

1 个答案:

答案 0 :(得分:2)

你必须修剪一个空间" BroadCategory"

"BroadCategory ": "BroadCategory2",

更改为:

"BroadCategory": "BroadCategory2",

OR:

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