题目描述
这是一个把一级部门json数据,转换成多级的js方法
相关代码
function transData(a, idStr, pidStr, chindrenStr) {
var r = [];
var hash = {};
var id = idStr;
var pid = pidStr;
var children = chindrenStr;
var i = 0;
var j = 0;
var len = a ? a.length : 0;
for (; i < len; i++) {
hash[a[i][id]] = a[i];
}
for (; j < len; j++) {
var aVal = a[j];
var hashVP = hash[aVal[pid]];
if (hashVP) {
!hashVP[children] && (hashVP[children] = []);
hashVP[children].push(aVal);
} else {
r.push(aVal);
}
}
return r;
}
疑问?
在方法内 r对象就被push了一次,但是r内的数据会跟着hashvp的改变而改变, 这是为什么呢
数据
id - pid格式的
[
{
"id": "123",
"pid": "11223",
"name": "部门4",
},
{
"id": "1122",
"pid": null,
"name": "部门1",
},
{
"id": "11223",
"pid": null,
"name": "部门2",
},
{
"id": "1111111",
"pid": "1122",
"name": "部门3",
},
{
"id": "1233221",
"pid": "123",
"name": "部门5",
}
]
转成id - children格式的
[
{
"id": "1122",
"pid": null,
"name": "部门1",
"children": [
{
"id": "1111111",
"pid": "1122",
"name": "部门3"
}
]
},
{
"id": "11223",
"pid": null,
"name": "部门2",
"children": [
{
"id": "123",
"pid": "11223",
"name": "部门4",
"children": [
{
"id": "1233221",
"pid": "123",
"name": "部门5"
}
]
}
]
}
]
没参数,我手动给你写一个吧,不是原生的,需要用到lodash,当然可以自行修改成原生的方法