Home > OS >  How can I group an array of objects by key and create another object inside
How can I group an array of objects by key and create another object inside

Time:04-29

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'
  }
]

CodePudding user response:

Expecting 'color' : { 'Blue','Yellow' } in your output is wrong. Objects are key-value pairs of data.

You want color to be an array and adjust your code.

build.forEach(pr => {
  if (pr.Product in result) {
      if (!result[pr['Product']]['Color']) {
        result[pr['Product']]['Color'] = [];
      }
      result[pr['Product']]['Color'].push(pr['Color']);
  } else {
      result[pr['Product']] = {
          'Product': pr['Product'],
          'Color': [pr['Color'] ]
      }
  }
});

CodePudding user response:

const builds = [
    { 'Product': 'Cabinets', 'Color': 'Blue' }, 
    { 'Product': 'CounterTop', 'Color': 'White' }, 
    { 'Product': 'Cabinets', 'Color': 'Yellow' }, 
    { 'Product': 'Cabinets', 'Color': 'Yellow' }
];

const results = [];

builds.forEach((build) => {
  const index = results.findIndex((b) => b.Product === build.Product);
  if (index === -1) {
    results.push({Product: build.Product, Color: [ build.Color ]});
  } else {
    results[index] = {Product: build.Product, Color: [ ...results[index].Color, build.Color ]}
  }
});

console.log(results);

  • Related