通常开发中后台给的数据是这样的基本格式,前端需要实现分类、地址等树形(层级关系)场景。思路[]->json->[]
let allDatas = [
{
id: 5,
name: 'ddddd',
parendId: 4
},
{
id: 3,
name: 'bbbb',
parendId: 1
},
{
id: 2,
name: 'aaaaa',
parendId: 3
},
{
id: 16,
name: 'jjjj',
parendId: ''
}
];
function toTreeData( data, config ){
var _id = "id";
var _pid = "parendId";
var _children = "children";
if( config ){
_id = config.id;
};
var map = {};
data.forEach(function (item) {
if( !item[_pid] ){
item[_pid] = '~';
};
var _idval = item[_id].toString();
map[_idval] = item;
});
var val = [];
data.forEach(function (item) {
var _pidval = item[_pid].toString();
var parent = map[ _pidval ];
if (parent) {
(parent[_children] || ( parent[_children] = [] )).push(item);
} else {
val.push(item);
};
});
return val;
}
console.log(toTreeData(allDatas))
网友评论