jsonTree(data, config)
var jsonTree = function (data,config) {
//1
var id = config.id || 'id',
pid = config.pid || 'pid',
children = config.children || 'children';
var idMap = [],
jsonTree = [];
//2
data.forEach(function(v){
idMap[v[id]] = v;
});
//3
data.forEach(function(v){
var parent = idMap[v[pid]];
if(parent) {
!parent[children] && (parent[children] = []);
parent[children].push(v);
} else {
jsonTree.push(v);
}
});
return jsonTree;
};
var data = [
{"id":1,"parent":0,"addr":"重庆"},
{"id":11,"parent":1,"addr":"重庆"},
{"id":12,"parent":1,"addr":"重庆"},
{"id":121,"parent":12,"addr":"重庆"},
{"id":2,"parent":0,"addr":"重庆"},
{"id":21,"parent":2,"addr":"重庆"},
{"id":211,"parent":21,"addr":"重庆"},
{"id":3,"parent":0,"addr":"重庆"},
{"id":4,"parent":0,"addr":"重庆"},
{"id":31,"parent":3,"addr":"重庆"},
{"id":32,"parent":3,"addr":"重庆"}
];
//调用
var result = jsonTree(data, {
id: 'id',
pid: 'parent',
children: 'list'
});
console.log(result)
console.log(JSON.stringify(result, null, '\t'));