If you want to turn the json into a tree structure according to the business department and the product line, how can you optimize it?

var obj1=[
  {
   "demp":"001",
   "line":"a",
   "id":"1",
   },
  {
   "demp":"001",
   "line":"b",
   "id":"2",
   },
  {
   "demp":"001",
   "line":"c",
   "id":"3",
   },
 {
   "demp":"002",
   "line":"a",
   "id":"4",
   },
{
   "demp":"002",
   "line":"b",
   "id":"5",
   },
{
   "demp":"002",
   "line":"b",
   "id":"6",
}
]
function trans(obj1,key1){
    var obj={};
var arr=[];
for(i in obj1){
 if(arr.indexOf(obj1[i][key1])=="-1"){
    arr.push(obj1[i][key1]);
   console.log(i);
 }
}
for(j in arr){
  for(k in obj1){
     if(obj1[k][key1]==arr[j]){
     if(obj[arr[j]]){
        obj[arr[j]].push(obj1[k]);
     }else{
       obj[arr[j]]=[obj1[k]];
      }
      
    }
  }
}
return obj;
}
var obj2=trans(obj1,"demp");
var newobj={};
for(i in obj2){
 obj2[i]=trans(obj2[i],"line");
}
console.log(obj2);-sharp-sharp-sharp 


-sharp-sharp-sharp 


-sharp-sharp-sharp 
// 


-sharp-sharp-sharp 
Jan.28,2022

first construct a small tree according to the product line, then aggregate the small tree into a big tree of each business department according to the business department, and finally aggregate into a whole tree


function createTree(arr,keys) {
  function createObj(arr, arrORobj, keys, start) {
    for (let i = 0; i < arr.length; iPP) {
      // key[]
      if (start >= keys.length) {
        let newArray=Array.isArray(arrORobj)?arrORobj:[]
        return newArray.concat(arr[i])
      }
      let curKey = keys[start]
      let curVal = arr[i][curKey]
      if(!curVal)continue
      // key{}
      let newObj = arrORobj[curVal] ? arrORobj[curVal] : {}
      arrORobj[curVal] = createObj([arr[i]], newObj, keys, start + 1)
    }
    // key{}
    return arrORobj
  }
  return createObj(arr,{},keys,0)
}
createTree(obj1,['demp','line'])
Menu