javascript 树形数据转化维数组
废话不多说直接上代码。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>遍历树</title>
</head>
<body>
<script>
window.onload = function () {
var data = [
{
"id": 1,
"text": "aa",
"children": [
{"id": 2, "text": "bb"},
{"id": 3, "text": "cc"},
{"id": 4, "text": "dd"},
{"id": 5, "text": "ee"},
{
"id": 6,
"text": "ff",
"children": [
{"id": 7, "text": "gg"},
{"id": 8, "text": "hh"},
]
}
]
},
{
"id": 10,
"text": "aa0",
"children": [
{"id": 20, "text": "bb0"},
{"id": 30, "text": "cc0"},
{"id": 40, "text": "dd0"},
{"id": 50, "text": "ee0"},
{
"id": 60,
"text": "ff0",
"children": [
{"id": 70, "text": "gg0"},
{"id": 80, "text": "hh0"},
]
}
]
}
];
console.log(convert_tree_data(data));
function convert_tree_data(data) {
for (var i = 0; i < data.length; i++) {
if (data[i].children != undefined) {
var temp = data[i].children;
// 删除孩子节点
delete data[i].children;
// 孩子节点加入数组末尾
for (var j = 0; j < temp.length; j++) {
data.push(temp[j]);
}
}
}
return data;
}
}
</script>
</body>
</html>