-1

I have this array with some objects,

var arr = [
  {type: "motorbike", model: "ducati monster 797", quantity: 2},
  {type: "car", model: "audi", quantity: 4},
  {type: "truck", model: "ford", quantity: 1},
  {type: "car", model: "bmw", quantity: 1},
  {type: "bicycle", model: "giant", quantity: 3},
  {type: "truck", model: "MAN", quantity: 1},
  {type: "car", model: "dodge 2012", quantity: 3}
]

how can i group the objects by the 'type' property of each object to get this format:

var arr2 = [
  {
    type: 'motorbike',
    data: [{model: "ducati monster 797", quantity: 2}]
  },
  {
    type: 'car',
    data: [
      {model: "audi", quantity: 4},
      {model: "bmw", quantity: 1},
      {model: 'dodge 2012', quantity: 3},
    ]
  },
  {
    type: 'truck',
    data: [
      {model: "ford", quantity: 1},
      {model: "MAN", quantity: 1}
    ]
  }
];
john
  • 796
  • 1
  • 13
  • 34
  • Have you done any research here? Did you try anything? What happened? – jonrsharpe Jul 30 '20 at 10:07
  • Does this answer your question? [How to group an array of objects by key](https://stackoverflow.com/questions/40774697/how-to-group-an-array-of-objects-by-key) – jonrsharpe Jul 30 '20 at 10:07

2 Answers2

0

You could use the rest parameter

var arr = [
  {type: "motorbike", model: "ducati monster 797", quantity: 2},
  {type: "car", model: "audi", quantity: 4},
  {type: "truck", model: "ford", quantity: 1},
  {type: "car", model: "bmw", quantity: 1},
  {type: "bicycle", model: "giant", quantity: 3},
  {type: "truck", model: "MAN", quantity: 1},
  {type: "car", model: "dodge 2012", quantity: 3}
]

  res= arr.map((rest) =>({type : rest.type,  
                     data : [{model : rest.model , quantity : rest.quantity}]}) )
  console.log(res)
Sven.hig
  • 4,449
  • 2
  • 8
  • 18
0

You can use .reduce(), .map() and Object.entries() to get the desired output:

const data = [
  {type: "motorbike", model: "ducati monster 797", quantity: 2},
  {type: "car", model: "audi", quantity: 4},
  {type: "truck", model: "ford", quantity: 1},
  {type: "car", model: "bmw", quantity: 1},
  {type: "bicycle", model: "giant", quantity: 3},
  {type: "truck", model: "MAN", quantity: 1},
  {type: "car", model: "dodge 2012", quantity: 3}
];

const result = Object.entries(data.reduce((r, {type, ...rest}) => {
  r[type] = r[type] || [];
  r[type].push(rest);
  return r;
}, {})).map(([type, data]) => ({type, data}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95