{
"ListBy": [{
"Type": 12,
"Basis": 808,
"Code": "bad",
"Rate": "10.00",
"type1": 811,
}, {
"Type": 12,
"Basis": 806,
"Code": "bad",
"Rate": "10.00",
"type1": 810,
}, {
"Type": 13,
"Basis": 805,
"Code": "good",
"Rate": "10.00",
"type1": 810,
}, {
"Type": 13,
"Basis": 805,
"Code": "good",
"Rate": "10.00",
"type1": 810,
}, {
"Type": 13,
"Code": "awesome",
"Basis": 805,
"Type": 810,
"Rate": "10.00"
}]
}
从REST
服务我获得上述数据。我必须使用json
(仅使用类型和代码)将以上duplicates
分组到以下分组数组中。
请使用underscore.js
或javascript中的任何预定义函数来帮助我。
注意:类型值始终为12
或13
。
{
"ListBy": [{
"Type": 12,
"Code": "bad"
"List": [{
"Basis": 808,
"type1": 811,
"Rate": "10.00"
},
{
"Basis": 806,
"type1": 810,
"Rate": "10.00"
}
]
},
{
"Type": 13,
"Code": "good",
"List": [{
"Basis": 805,
"Type": 810,
"Rate": "10.00"
},
{
"Basis": 805,
"Type": 810,
"Rate": "10.00"
}]
},
{
"Type": 13,
"Code": "awesome",
"List": [{
"Basis": 805,
"Type": 810,
"Rate": "10.00"
}]
}
]
}
答案 0 :(得分:0)
我正在使用lodash
var groups = _.groupBy(data.ListBy, function(value){
return value.Type + '#' + value.Code;
});
var result = _.map(groups, function(group){
return {
type: group[0].Type,
code: group[0].Code,
Lists: _.map(group,function(item){
return {
Basis : item.Basis,
Type1 : item.type1,
Rate : item.Rate
}
})
}
});
如果要转换为原始数据
var result = [];
_.each(data.ListBy,function(item){
_.each(item.List,function(nestItem){
result.push({
Type : item.Type,
Code : item.Code,
Basis: nestItem.Basis,
Type1: nestItem.Type,
Rate: nestItem.Rate
});
})
});
答案 1 :(得分:0)
在普通的ES6中,您可以使用reduce
累加器对象来执行此操作,通过串联两个关键字段来键入。最终结果包含该累加器对象的值数组:
const data = {ListBy: [{Type: 12,Basis: 808,Code: "bad",Rate: "10.00",type1: 811,}, {Type: 12,Basis: 806,Code: "bad",Rate: "10.00",type1: 810,}, {Type: 13,Basis: 805,Code: "good",Rate: "10.00",type1: 810,}, {Type: 13,Basis: 805,Code: "good",Rate: "10.00",type1: 810,}, {Type: 13,Basis: 805,Code: "awesome",Rate: "10.00",type1: 810}]};
const result = {
ListBy: Object.values(
data.ListBy.reduce( (acc, {Type, Code, Basis, Rate, type1}) => {
(acc[Type+Code] = acc[Type+Code] || {Type, Code, List: []})
.List.push({Basis, Rate, type1});
return acc;
}, {} )
)
};
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
串联是一种安全的解决方案,因为Type
字段的长度始终相同(即12或13转换为字符串时为2个字符)。如果不是这种情况,则应使用分隔符,您确定它不会出现在任何这些键值中。