js根据id、pid把数据转为树结构

//格式化树数据
function toTreeData(data) {
var pos = {};
var tree = [];
var i = 0;
while (data.length != 0) {
if (data[i].pId == '0') {
tree.push({
id: data[i].id,
name: data[i].name,
children: []
});
pos[data[i].id] = [tree.length - 1];
data.splice(i, 1);
i--;
} else {
var posArr = pos[data[i].pId];
if (posArr != undefined) {

var obj = tree[posArr[0]];
for (var j = 1; j < posArr.length; j++) {
obj = obj.children[posArr[j]];
}

obj.children.push({
id: data[i].id,
name: data[i].name,
children: []
});
pos[data[i].id] = posArr.concat([obj.children.length - 1]);
data.splice(i, 1);
i--;
}
}
i++;
if (i > data.length - 1) {
i = 0;
}
}
return tree;
}

上一篇:PC_android通信之传输图片并显示在手机端【转】


下一篇:ios NSString 转 float的注意