我很难弄清楚如何对对象数组中的多个数据进行分组。我的第一个代码显示了如何根据我的第一个数据formuleWazari进行分组。我想在这一组之后再做一组。
我的代码:
const groupBy = (array, key) => {
// Return the end result
return array.reduce((result, currentValue) => {
// If an array already present for key, push it to the array. Else create an array and push the object
(result[formuleWazari(currentValue[key])] = result[formuleWazari(currentValue[key])] || []).push(
new wazari(currentValue['product'], currentValue['warranty'])
// new wazariFinal(currentValue['warranty'])
);
// Return the current iteration `result` value, this will be taken as next iteration `result` value and accumulate
return result;
}, {}); // empty object is the initial value for result object
};
var personGroupedByColor = groupBy(obj.warrantySettings, 'formula');这段代码给出了这样的结果:
{
"Basic": [
{
"product": 3,
"warranty": 1
},
{
"product": 3,
"warranty": 8
},
{
"product": 3,
"warranty": 6
},
{
"product": 4,
"warranty": 7
},
{
"product": 4,
"warranty": 14
}
],
"Confort": [
{
"product": 3,
"warranty": 1
},
{
"product": 3,
"warranty": 8
},
{
"product": 3,
"warranty": 2
},
{
"product": 3,
"warranty": 3
},
{
"product": 3,
"warranty": 10
},
{
"product": 3,
"warranty": 11
},
{
"product": 3,
"warranty": 6
},
{
"product": 4,
"warranty": 7
},
{
"product": 4,
"warranty": 14
}
],
}我想再按产品分组。我怎么做才能让json看起来像这样(提前感谢那些帮助我的人):
{
"Basic": [
{ "product":[
3 :{
"warranty": 1,
"warranty": 8
},
4 :{
"warranty": 10,
"warranty": 12
},
]
]}}发布于 2020-04-06 23:51:50
我找到了解决方案:
const groupBy = (array, key) => {
// Return the end result
return array.reduce((result, currentValue) => {
// If an array already present for key, push it to the array. Else create an array and push the object
(result[formuleWazari(currentValue[key])] = result[formuleWazari(currentValue[key])] || []).push(
);
(result[formuleWazari(currentValue[key])] [productWazari(currentValue['product'])] = result[formuleWazari(currentValue[key])] [productWazari(currentValue['product'])] || []).push(
garantieWazari(currentValue['warranty'])
);
// Return the current iteration `result` value, this will be taken as next iteration `result` value and accumulate
return result;
}, {}); // empty object is the initial value for result object
};https://stackoverflow.com/questions/61061031
复制相似问题