首页 > 解决方案 > 如何根据属性对对象进行分组

问题描述

希望可以有人帮帮我,

情况: 我正在开发一个单元报告,我在其中选择所有带有 unit_id 的客户(unit_id 是与单元的关系,它们可以在哪里找到),这个选择是一个对象数组,我有如何根据一个特定属性对对象进行分组时遇到了麻烦,我有一个数组,例如:

const clients = [
  [
    {
      ID: 1,
      NAME: 'John Doe',
      UNITS: ['02'],
    }
  ],
  [
    {
      ID: 2,
      NAME: 'Jane Doe',
      UNITS: ['01', '02'],
    }
  ],
  [
    {
      ID: 3,
      NAME: 'Doe John',
      UNITS: ['50', '15'],
    }
  ],
  [
    {
      ID: 4,
      NAME: 'Doe Jane',
      UNITS: ['30'],
    }
  ],
  [
    {
      ID: 5,
      NAME: 'Doe Jane',
      UNITS: ['15'],
    }
  ],
]

问题:我需要用相同的“ UNIT ” 对每个人进行分组,但是我不能在一个组中拥有多个具有相同“ UNIT ID ”的组,我期待的结果如下:

const unitGroups = [
  [
    {
      UNIT_IDS: ['01', '02'],
      CLIENTS: [
        {
          ID: 1,
          NAME: 'John Doe',
        }, 
        {
          ID: 2,
          NAME: 'Jane Doe',
        }
      ]
    }
  ],
  [
    {
      UNIT_IDS: ['50', '15'],
      CLIENTS: [
        {
          ID: 3,
          NAME: 'Doe John',
        },
        {
          ID: 5,
          NAME: 'Doe Jane',
        }
      ]
    }
  ],
  [
    {
      UNIT_IDS: ['30'],
      CLIENTS: [
        {
          ID: 4,
          NAME: 'Doe Jane',
        }
      ]
    }
  ]
]

标签: javascriptnode.jslogiclodashbackend

解决方案


你可以利用reduce以达到效果。这是一个实现:

const clients = [ [ { ID: 1, NAME: 'John Doe', UNITS: ['02'], } ], [ { ID: 2, NAME: 'Jane Doe', UNITS: ['01', '02'], } ], [ { ID: 3, NAME: 'Doe John', UNITS: ['50', '15'], } ], [ { ID: 4, NAME: 'Doe Jane', UNITS: ['30'], } ], [ { ID: 5, NAME: 'Doe Jane', UNITS: ['15'], } ]];

const result = clients.reduce((a,e)=>{
   e.forEach(({UNITS, ...rest})=>{
    const getIndex = a.findIndex(p=>p.UNIT_IDS.some(b=>UNITS.some(c=>c===b)));
    if(getIndex===-1){
       const newData = {UNIT_IDS:UNITS, CLIENTS:[].concat(rest)};
       a.push(newData);
       } else {
       a[getIndex].UNIT_IDS = [...new Set([...a[getIndex].UNIT_IDS, ...UNITS])];
       a[getIndex].CLIENTS = [...a[getIndex].CLIENTS, rest]
       }
    })
  return a;
},[]);

console.log(result);


推荐阅读