我正在开发一个应用程序,我需要根据该应用程序合并同一部门的对象
第二个Array中提供的条件,并将该关系附加到对象。

let inArr1 = [{"D1D2":"AND"},{"D3D4":"OR"}]
let inArr2 =[{"ID":"1","NAME":"KEN","DEPT1":"CSE"},
              {"ID":"2","NAME":"MARK","DEPT2":"IT"},
              {"ID":"3","NAME":"TOM","DEPT3":"ECE"},
              {"ID":"4","NAME":"SHIV","DEPT4":"LIB"},
              {"ID":"5","NAME":"TIM","DEPT5":"SEC"}
            ]


输出量

 outArr ={
                 [{"ID":"1","NAME":"KEN","DEPT1":"CSE","REL":"AND"},
                  {"ID":"2","NAME":"MARK","DEPT2":"IT","REL":"AND"}], //Arr1
                 [{"ID":"3","NAME":"TOM","DEPT3":"ECE","REL":"OR"},
                  {"ID":"4","NAME":"SHIV","DEPT4":"LIB","REL":"OR"}], //Arr2
                 [{"ID":"5","NAME":"TIM","DEPT5":"SEC"}]              //Arr3
                }


码:

let  condArr=[],outArr,i=1;

inArr1.forEach(condt => {
     let dept = Object.keys(condt)[0];
     let tmparr = dept.split("D");
     tmparr.shift()
     condArr.push(tmparr)
   });

inArr2.forEach(condt => {
    if(condArr.includes(inArr2.D+i)){
        i++;
       outArr.push(inArr2);
    }
 });

最佳答案

您的代码逻辑有点混乱,我建议这样做

let inArr1 = [{"D1D2":"AND"},{"D3D4":"OR"},{"D5D6":"AND"}]
let inArr2 =[{"ID":"1","NAME":"KEN","DEPT1":"CSE"},
              {"ID":"2","NAME":"MARK","DEPT2":"IT"},
              {"ID":"3","NAME":"TOM","DEPT3":"ECE"},
              {"ID":"4","NAME":"SHIV","DEPT4":"LIB"},
              {"ID":"5","NAME":"TIM","DEPT5":"SEC"},
              {"ID":"6","NAME":"TLA","DEPT6":"SEC"},
            ]

// first lets create object of ids as keys and conditions as values
const [keys, conditions] = inArr1.reduce((agg, cond, index) => {
   Object.entries(cond).forEach(([key, value]) => {
      key.split('D').forEach(v => { if (v) agg[0][v] = { value, index }})
      agg[1].push([])
   })
   return agg
}, [{}, []]) // {1: "AND", 2: "AND", 3: "OR", 4: "OR"}
conditions.push([])

// and now just map over all elements and add condition if we found id from the keys
inArr2.forEach(item => {
   const cond = keys[item.ID]
   if (cond) conditions[cond.index].push({...item, REL: cond.value})
   else conditions[conditions.length - 1].push(item)
})

const res = conditions.filter(v => v.length)
console.log(res)

10-08 19:05