'Lodash groupBy multiple keys & keys inside arrays
I have this array below:
const products = [
{
isEqual: true,
cfop: 1,
tributes: [
{
tributeName: 'IPI',
cst: 50,
aliquot: 0.1
},
{
tributeName: 'PIS',
cst: 15,
aliquot: null
},
{
tributeName: 'ICMS',
cst: 1,
aliquot: null,
orig: 'SP'
},
{
tributeName: 'ICMS ST',
mva: 10,
aliquot: null,
},
]
},
{
isEqual: true,
cfop: 1,
tributes: [
{
tributeName: 'IPI',
cst: 50,
aliquot: 0.1
},
{
tributeName: 'PIS',
cst: 15,
aliquot: null
},
{
tributeName: 'ICMS',
cst: 10,
aliquot: null,
orig: 'SP'
},
{
tributeName: 'ICMS ST',
mva: 10,
aliquot: null,
},
]
},
{
isEqual: false,
cfop: 2,
tributes: [
{
tributeName: 'IPI',
cst: 50,
aliquot: 0.2
},
{
tributeName: 'PIS',
cst: 10,
aliquot: null
},
{
tributeName: 'ICMS',
cst: 10,
aliquot: null,
orig: 'SP'
},
{
tributeName: 'ICMS ST',
mva: 10,
aliquot: null,
},
]
}
]
I want to group the following properties if they're equal: "cfop" and "tributes.cst". But I will only compare this if "tributes.tributeName" === 'ICMS'. Maybe I should use a filter? I don't know. So the return would be:
const output = {
1: [
{
isEqual: true,
cfop: 1,
tributes: [
{
tributeName: 'IPI',
cst: 50,
aliquot: 0.1
},
{
tributeName: 'PIS',
cst: 15,
aliquot: null
},
{
tributeName: 'ICMS',
cst: 1,
aliquot: null,
orig: 'SP'
},
{
tributeName: 'ICMS ST',
mva: 10,
aliquot: null,
},
]
},
{
isEqual: true,
cfop: 1,
tributes: [
{
tributeName: 'IPI',
cst: 50,
aliquot: 0.1
},
{
tributeName: 'PIS',
cst: 15,
aliquot: null
},
{
tributeName: 'ICMS',
cst: 1,
aliquot: null,
orig: 'SP'
},
{
tributeName: 'ICMS ST',
mva: 10,
aliquot: null,
},
]
},
],
2: [
{
isEqual: false,
cfop: 2,
tributes: [
{
tributeName: 'IPI',
cst: 50,
aliquot: 0.2
},
{
tributeName: 'PIS',
cst: 10,
aliquot: null
},
{
tributeName: 'ICMS',
cst: 10,
aliquot: null,
orig: 'SP'
},
{
tributeName: 'ICMS ST',
mva: 10,
aliquot: null,
},
]
}
]
}
]
Tried a few things with lodash and lodash.groupBy but couldn't achieve. How can I do so? Thanks!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
