合并具有关系的对象数组

问题描述 投票:-1回答:1

我有一个棘手的要求,我需要根据另一个对象数组中提供的关系来组合对象数组。

关系将始终在1&2,3&4,5&6之间,并且值可以为AND / OR。

关系:

let relations = [{"L5L6":"AND"}];

let approvers= [{"NAME":"Tom","POSITION":"MANAGER","LEVEL":6},
                {"NAME":"Lisa","POSITION":"ASM-2","LEVEL":5},
                {"NAME":"Robert","POSITION":"RGM","LEVEL":4},
                {"NAME":"Thomas","POSITION":"ASM-1","LEVEL":5}]

基于关系数组(L1,L2 => 1),(L3,L4)=> 3,(L5,L6)=> 5组合两个数组。

let output  = [{LEVEL:5,
                NAME1:"LISA",
                POSITION1:"ASM-2",
                NAME2:"Thomas",
                POSITION2:"ASM-1",
                NAME3:"Tom",
                POSITION3:"MANAGER",
                RELATION : "AND"
              },
              {LEVEL:4,
             NAME :"Robert",
             POSITION:"RGM"
             }]            

我能够使用相同的级别合并数组,但无法合并。

const group = _.groupBy(approvers, 'LEVEL'); 

    return Object.entries(group).map( ([LEVEL, array]) => {

      return array.reduce((acc, cur, idx) => ({
        ...acc, 
        ['NAME' + (idx + 1)]: cur.FULLNAME ,
        ['POSITION' + (idx + 1)]: cur.POSITION ,

      }), { LEVEL });
    })
javascript lodash
1个回答
0
投票

我创建了queryApprovers函数以部分满足您的要求以及Loi Nguyen Huynh对您的问题的this thread答案。结合起来,您将获得所需的结果:

let relations = [{"L5L6":"AND"}];

let approvers= [{"NAME":"Tom","POSITION":"MANAGER","LEVEL":6},
                {"NAME":"Lisa","POSITION":"ASM-2","LEVEL":5},
                {"NAME":"Robert","POSITION":"RGM","LEVEL":4},
                {"NAME":"Thomas","POSITION":"ASM-1","LEVEL":5}];
                


const queryApprovers = (approvers, relations) => {
   let newApprovers = [];
   relations.forEach(relation => {
      let levels = Object.keys(relation)[0];
      let levelsArr = levels.split("L");
      levelsArr.shift();
      approvers.forEach(approver => {
         if(levelsArr.includes(approver.LEVEL.toString())){
            newApprovers.push(approver);
         }
      });
   });
   return newApprovers;
};

function groupByLevel(approvers) {
  const group = _.groupBy(approvers, 'LEVEL');
  // console.log(group); // try logging to see what we have

  return Object.entries(group).map( ([LEVEL, array]) => {

    return array.reduce((acc, cur, idx) => ({
      ...acc,
      ['EMAIL'    + (idx + 1)]: cur.EMAIL    ,
      ['FULLNAME' + (idx + 1)]: cur.FULLNAME ,
      ['POSITION' + (idx + 1)]: cur.POSITION ,
      ['SLA'      + (idx + 1)]: cur.SLA      ,
      ['STATUS'   + (idx + 1)]: cur.STATUS   ,

    }), { LEVEL });
  })
}

let groupedByLevel = groupByLevel(approvers);

console.log(queryApprovers(groupedByLevel, relations));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>
热门问题
推荐问题
最新问题