如何根据属性对对象进行分组

时间:2020-10-02 12:40:42

标签: javascript node.js logic lodash backend

希望有人可以帮助我

情况: 我正在开发一个单位报告,在这里我选择所有具有其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',
        }
      ]
    }
  ]
]

2 个答案:

答案 0 :(得分:1)

您可以使用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);

答案 1 :(得分:0)

const intersection = (array1, array2) =>
  array1.filter((value) => array2.includes(value));

const results = [];

for (const { ID, NAME, UNITS } of clients.flat()) {
  const contain = results.find(({ UNIT_IDS }) =>
    intersection(UNIT_IDS, UNITS).length
  );

  if (contain) {
    contain.CLIENTS.push({ ID, NAME });

    if (UNITS.length > contain.UNIT_IDS.length) {
      contain.UNIT_IDS = UNITS;
    }

    continue;
  }

  results.push({
    UNIT_IDS: UNITS,
    CLIENTS: [
      { ID, NAME },
    ],
  });
}

console.log(results.map((group) => [group]));