json转树形结构 json转树形结构

json转树形结构

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);

按照事业部产品线拆分,程序有待优化

经过优化后:

function createTree(arr,keys) {
  function createObj(arr, arrORobj, keys, start) {
    for (let i = 0; i < arr.length; i++) {
      // 当不存在一个排序的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'])

分享本文至:

评论 0

挤眼 亲亲 咆哮 开心 想想 可怜 糗大了 委屈 哈哈 小声点 右哼哼 左哼哼 疑问 坏笑 赚钱啦 悲伤 耍酷 勾引 厉害 握手 耶 嘻嘻 害羞 鼓掌 馋嘴 抓狂 抱抱 围观 威武 给力
提交评论

清空信息
关闭评论