I have an array that I need group by a certain property ("name").
[
{
"name": "cor",
"value": "#e61809",
"sku": "SKU-BICI-EST-TREKMAD-SLR9"
},
{
"name": "cor",
"value": "#3e7555",
"sku": "SKU-BICI-EST-TREKMAD-SLR9-1"
},
{
"name": "tamanho",
"value": "m",
"sku": "SKU-BICI-EST-TREKMAD-SLR9"
},
{
"name": "tamanho ",
"value": "L",
"sku": "SKU-BICI-EST-TREKMAD-SLR9-1"
}
]
and I need to convert to:
{ cor: [{
"name": "cor",
"value": "#e61809",
"sku": "SKU-BICI-EST-TREKMAD-SLR9"
},
{
"name": "cor",
"value": "#3e7555",
"sku": "SKU-BICI-EST-TREKMAD-SLR9-1"
}],
tamanho:[{
"name": "tamanho",
"value": "m",
"sku": "SKU-BICI-EST-TREKMAD-SLR9"
},
{
"name": "tamanho ",
"value": "L",
"sku": "SKU-BICI-EST-TREKMAD-SLR9-1"
}]
}
const groupedMap = variantsAttrs.reduce(
(entryMap, e) => entryMap.set(e.name, [...entryMap.get(e.name)||[], e]),
new Map()
)
2
Answers
You’re almost there with
reduce
. I simplify it a bitIf you want a Map, use
Map.groupBy()
:To create an 2d array after grouping by key, use
Object.groupBy()
, and then convert back to any array withArray.values()
: