将如下扁平对象,转为树形对象。parent
字段为空字符串的节点为根节点:
var input = {
h3: {
parent: 'h2',
name: '副总经理(市场)'
},
h1: {
parent: 'h0',
name: '公司机构'
},
h7: {
parent: 'h6',
name: '副总经理(总务)'
},
h4: {
parent: 'h3',
name: '销售经理'
},
h2: {
parent: 'h1',
name: '总经理'
},
h8: {
parent: 'h0',
name: '财务总监'
},
h6: {
parent: 'h4',
name: '仓管总监'
},
h5: {
parent: 'h4',
name: '销售代表'
},
h0: {
parent: '',
name: 'root'
}
};
var plain2Tree = function (obj) {
var key, res
for(key in obj) {
var parent = obj[key].parent
if(parent === '') {
res = obj[key]
} else {
obj[parent][key] = obj[key]
}
}
return res
}
下列数据整理成级联选择数据:
最终数据:
var data = [{
"value": "浙江",
"children": [{
"value": "杭州",
"children": [{
"value": "西湖"
}]
}]
}, {
"value": "四川",
"children": [{
"value": "成都",
"children": [{
"value": "锦里"
}, {
"value": "方所"
}]
}, {
"value": "阿坝",
"children": [{
"value": "九寨沟"
}]
}]
}]
原始数据:
var data = [{
"province": "浙江",
"city": "杭州",
"name": "西湖"
}, {
"province": "四川",
"city": "成都",
"name": "锦里"
}, {
"province": "四川",
"city": "成都",
"name": "方所"
}, {
"province": "四川",
"city": "阿坝",
"name": "九寨沟"
}]
var transObject = function(tableData, keys) {
let hashTable = {}, res = []
for (let i = 0; i < tableData.length; i++) {
let arr = res, cur = hashTable
for (let j = 0; j < keys.length; j++) {
let key = keys[j], filed = tableData[i][key]
if (!cur[filed]) {
let pusher = {
value: filed
}, tmp
if (j !== (keys.length - 1)) {
tmp = []
pusher.children = tmp
}
cur[filed] = { $$pos: arr.push(pusher) - 1 }
cur = cur[filed]
arr = tmp
} else {
cur = cur[filed]
arr = arr[cur.$$pos].children
}
}
}
return res
}