我使用lodash的_.groupBy来提供以下数据:
{
"Generic Drugs":[
{
itemDes: "Dulcolax",
itemGeneric: "Bisacodyl",
price: '10'
},
{
itemDes: "Celine",
itemGeneric: "Ascorbic Acid",
price: '10'
},
{
itemDes: "Vitamic C",
itemGeneric: "Ascorbic Acid",
price: '10'
}
],
"None-generic Drugs" : [
{
itemDes: "test 1",
itemGeneric: "",
price: '10'
},
{
itemDes: "test 2",
itemGeneric: "",
price: '10'
}
]
}
我想通过属性itemGeneric将Generic Drugs对象中的对象分组,得到如下输出:
{
"Generic Drugs":[
"Ascorbic Acid" : [
{ itemDes: "Celine" },
{ itemDesc: "Vitamin C" }
],
"Bisacodyl" : [
{ itemDes: "Dolculax" }
]
"None-generic Drugs" : [
{
itemDes: "test 1",
itemGeneric: "",
price: '10'
},
{
itemDes: "test 2",
itemGeneric: "",
price: '10'
}
]
}
请有人帮我解决这个问题。谢谢你的回答。 :)
答案 0 :(得分:2)
对分组数据使用_.mapValues()
,并按'itemGeneric'对每个值进行分组:
_.mapValues(grouped, function(group, key) {
return key === 'Generic Drugs' ? _.groupBy(group, 'itemGeneric') : group;
});
var grouped = {
"Generic Drugs": [{
itemDes: "Dulcolax",
itemGeneric: "Bisacodyl",
price: '10'
}, {
itemDes: "Celine",
itemGeneric: "Ascorbic Acid",
price: '10'
}, {
itemDes: "Vitamic C",
itemGeneric: "Ascorbic Acid",
price: '10'
}],
"None-generic Drugs": [{
itemDes: "test 1",
itemGeneric: "",
price: '10'
}, {
itemDes: "test 2",
itemGeneric: "",
price: '10'
}]
};
var result = _.mapValues(grouped, function(group, key) {
return key === 'Generic Drugs' ? _.groupBy(group, 'itemGeneric') : group;
});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
如果原始数据项是这样的:
{
type: "Generic Drugs",
itemDes: "Dulcolax",
itemGeneric: "Bisacodyl",
price: '10'
}
你可以这样做:
_(originalData).groupBy('type').mapValues(grouped, function(group, key) {
return key === 'Generic Drugs' ? _.groupBy(group, 'itemGeneric') : group;
});