
如何使用 javascript 递归将树结构数据转换为列表数据
在面试中,你可能会遇到要求使用 javascript 将树形结构数据转换成列表数据的问题。为了解决这一问题,你可以使用递归。
/**
input: [{
id: 1,
text: 'text1',
children: [{
id: 2,
text: 'text2',
parentId: 1,
children: [{
id: 4,
text: 'text4',
parentId: 2
}]
}, {
id: 3,
text: 'text3',
parentId: 1
}]
}]
output: [{
id: 4,
text: 'text4',
parentId: 2
}, {
id: 2,
text: 'text2',
parentId: 1
}, {
id: 3,
text: 'text3',
parentId: 1
}, {
id: 1,
text: 'text1'
}, ];
**/
function walk(list) {
var output = [];
list.forEach(function(item) {
if (item.children) {
output = output.concat(walk(item.children));
delete item.children;
}
output.push(item);
});
return output;
}在代码中:
通过这种方式,您可以递归地遍历给定的树形结构,并将所有节点转换为一个列表数据。
立即学习“Java免费学习笔记(深入)”;
以上就是如何使用 JavaScript 递归将树形结构数据转换为列表数据?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号