JavaScript中对象列表的分组

时间:2019-08-16 05:28:07

标签: javascript arrays sorting grouping

从函数[{…},{…},{…}]的输出中,我得到了类似的东西,看起来像所提供的代码片段。

我想按系统标签将其与上面所需的输出分组。 GroupBy只给我一个对象。

  [
     {
       id: 100,
       system: {id: 101, label: "BLUE", createdAt: "2019-07-30"},
       details: [{...},{...}],
       info: "Test1"
     },
     {
       id: 400,
       system: {id: 404, label: "RED", createdAt: "2019-10-30"},
       details: [{...},{...}],
       info: "Test2"
     },
     {
       id: 800,
       system: {id: 404, label: "RED", createdAt: "2019-10-30"},
       details: [{...},{...}],
       info: "Test3"
     }
   ]

我想要这样的东西,它按系统标签分组:

const after= [
  {
    color: 'BLUE',
    types: [{
             id: 100,
             system: {id: 101, label: "BLAU", createdAt: "2019-07-30"},
             details: [{...},{...}],
             info: "Test1"
           }]
  },
  {
    color: 'RED',
    types: [{
             id: 400,
             system: {id: 404, label: "RED", createdAt: "2019-10-30"},
             details: [{...},{...}],
             info: "Test2"
           },
           {
             id: 800,
             system: {id: 404, label: "RED", createdAt: "2019-10-30"},
             details: [{...},{...}],
             info: "Test2"
           }]
  }
];

2 个答案:

答案 0 :(得分:0)

一种选择是使用reduce汇总数组并将Map用作累加器。

let arr = [{"id":100,"system":{"id":101,"label":"BLUE","createdAt":"2019-07-30"},"details":[],"info":"Test1"},{"id":400,"system":{"id":404,"label":"RED","createdAt":"2019-10-30"},"details":[],"info":"Test2"},{"id":800,"system":{"id":404,"label":"RED","createdAt":"2019-10-30"},"details":[],"info":"Test3"}];

let result = [...arr.reduce((c, v) => {
  let k = v.system.label;
  if (!c.has(k)) c.set(k, {color: k,types: []});
  c.get(k).types.push(v);
  return c;
}, new Map).values()];

console.log(result);

答案 1 :(得分:0)

您可以使用Array.prototype.reduce来对系统标签进行分组,然后获得类似的对象值

const data = [
     {
       id: 100,
       system: {id: 101, label: "BLUE", createdAt: "2019-07-30"},
       shape: {id: 404, label: "round", createdAt: "2019-10-30"},
       details: [{},{}],
       info: "Test1"
     },
     {
       id: 400,
       shape: {id: 405, label: "square", createdAt: "2019-10-30"},
       system: {id: 404, label: "RED", createdAt: "2019-10-30"},
       details: [{},{}],
       info: "Test2"
     },
     {
       id: 800,
       shape: {id: 406, label: "round", createdAt: "2019-10-30"},
       system: {id: 404, label: "RED", createdAt: "2019-10-30"},
       details: [{},{}],
       info: "Test3"
     }
   ]
   
const res = data.reduce((acc, item) => {
   if(acc[item.system.label]) {
      acc[item.system.label].typen.push(item);
      acc[item.system.label].shape.push(item.shape.label);
   } else {
      acc[item.system.label] = {
         color: item.system.label,
         shape: [item.shape.label],
         typen: [item]
      }
   }
   return acc;
}, {})

console.log(Object.values(res));