Does anyone know how to group an array of objects by an object key and then create a new array of objects based on the grouping? For example, I have an array of Build objects as below and I want to group by products and create another object of colors and price based on that.
build = [
{
'Product': 'Cabinets',
'Color': 'Blue',
},
{
'Product': 'CounterTop',
'Color': 'White',
},
{
'Product': 'Cabinets',
'Color': 'Yellow',
},
{
'Product': 'Cabinets',
'Color': 'Yellow',
}
]
And I want it like this
[
{
'Product':'Cabinet',
'color' : { 'Blue','Yellow' }
},
{
'Product':'CounterTop',
'color' : { 'White' }
}
]
I wrote a code to archive it but I am not getting the result as expected.
build.forEach(pr => {
if (pr.Product in result) {
result[pr['Product']]['Color'] = pr['Color'];
}
else {
result[pr['Product']] = {
'Product': pr['Product'],
'Color': pr['Color']
}
}
});
Above code returns
[
{
'Product':'Cabinet',
'color' : 'Yellow'
},
{
'Product':'CounterTop',
'color' : 'White'
}
]
result[pr['Product']]['Color'] = pr['Product']. You need to Array.push or use array spread to update any existing array assigned toColorColorto be an array in your output. In your exampleColoris an object which expects a key-value pair.color: { "blue", "yellow" }is not a valid structure. May be it should be:color: ["blue", "yellow"]. Next, 2) The string"Cabinets"(plural) becomes"Cabinet"in expected output. Is this a typo & it should actually be"Cabinets"in bothbuild& expected-output?. And, finally 3) There are two"Yellow"cabinets inbuild- but only one in expected-output. Do you need to remove duplicates - or was it a typo?