05 - json转成树状结构

时间:2022-10-15 00:08:11
       var jsonData = eval(`[
{"id":"4","pid":"1","name":"大家电"},
{"id":"5","pid":"1","name":"生活电器"},
{"id":"1","pid":"0","name":"家用电器"},
{"id":"2","pid":"0","name":"服饰"},
{"id":"3","pid":"0","name":"化妆"},
{"id":"7","pid":"4","name":"空调"},
{"id":"8","pid":"4","name":"冰箱"},
{"id":"9","pid":"4","name":"洗衣机"},
{"id":"10","pid":"4","name":"热水器"},
{"id":"11","pid":"3","name":"面部护理"},
{"id":"12","pid":"3","name":"口腔护理"},
{"id":"13","pid":"2","name":"男装"},
{"id":"14","pid":"2","name":"女装"},
{"id":"15","pid":"7","name":"海尔空调"},
{"id":"16","pid":"7","name":"美的空调"},
{"id":"19","pid":"5","name":"加湿器"},
{"id":"20","pid":"5","name":"电熨斗"}
]`); function transData(data, idStr, pidStr, chindrenStr) {
var arr = [],
hash = {},
id = idStr,
pid = pidStr,
children = chindrenStr; for (var i = 0; i < data.length; i++) {
hash[data[i][id]] = data[i];
}
for (var j = 0; j < data.length; j++) {
//data 中每一项
var arrVal = data[j],
//找父分类
hashVP = hash[arrVal[pid]];
//pid 不为 0
if (hashVP) {
!hashVP[children] && (hashVP[children] = []);
hashVP[children].push(arrVal);
}
//pid 为 0
else {
// 将data 的对象添加到数组中
arr.push(arrVal);
}
}
return arr;
} var jsonDataTree = transData(jsonData, 'id', 'pid', 'chindren');
console.log(jsonDataTree);