json转树形结构
emer 发布于 2018-12-11 17:57 2916 次阅读
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'])