树结构的数据扁平化
function flattenTree(data) {
data = JSON.parse(JSON.stringify(data));
var res = [];
while(data.length) {
var node = data.shift();
if (node.children && node.children.length) {
data = data.concat(node.children);
}
delete node.children;
res.push(node);
}
return res;
}
我们用一个数据来测试:
var tree = [{
id: 1,
name: '1',
children: [{
id: 2,
name: '2',
children: [{
id: 3,
name: '3',
children: [{
id: 4,
name: '4'
}]
}, {
id: 6,
name: '6'
}]
}]
}, {
id: 5,
name: '5'
}]
使用:
console.log(flattenTree(tree));
打印结果:
作者:tntxia
来源:juejin.cn/post/7260500913848090661
来源:juejin.cn/post/7260500913848090661