如何按对象属性对对象进行分组

时间:2020-07-30 10:05:10

标签: javascript arrays

我有一些对象的数组,

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

我如何通过每个对象的'type'属性将对象分组以获得这种格式:

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

2 个答案:

答案 0 :(得分:0)

您可以使用rest参数

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)

答案 1 :(得分:0)

您可以使用.reduce().map()Object.entries()获得所需的输出:

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; }