How to convert the following object into the following output in JavaScript?
[
{
"attrTitle": "color",
"attrValue": "Green"
},
{
"attrTitle": "size",
"attrValue": "M"
},
{
"attrTitle": "size",
"attrValue": "L"
},
{
"attrTitle": "size",
"attrValue": "S"
},
{
"attrTitle": "color",
"attrValue": "Red"
}
]
Output I expected is the following
[
{
"attrTitle": "color",
"attrValue": ["Red", "Green"]
},
{
"attrTitle": "size",
"attrValue": ["S","L","M"]
}
]
When I try with this code it does not work.
const variantAttr = productAttr.reduce((i, attr) => {
const { attrTitle, attrValue } = attr
i[attrTitle] = i[attrTitle] ?? []
i[attrTitle].push(attrValue)
return i
}, {})