JS 删除树状结构数据中空children
如何让自己在开发中能成长更快?开发效率更高?答案就是:不断学习,不断总结。在实际前端开发中,使用组件可以很快的开发出一个功能,比如ElementUI树形结构组件。那么使用组件就得返回组件规定的数据结构。数据大部分是在后端处理后直接返回需要的数据,比如PHP、JAVA等后端语言。可有时候也需要前端自己处理数据。下面雷雪松就给大家分享一个删除树状结构数据中空children的函数。
1 2 3 4 5 6 7 8 9 | function removeEmptyChildren (node) { node.forEach(item => { if ('children' in item && item.children.length === 0) { delete item.children } else if ('children' in item && item.children.length) { removeEmptyChildren(item.children) } }) } |
处理前数据实例:
1 2 3 4 5 6 7 8 9 10 11 12 | [{ label: '一级 2', children: [{ label: '二级 2-1', children: [{ label: '三级 2-1-1' }] }, { label: '二级 2-2', children: [] }] }] |
处理后数据:
1 2 3 4 5 6 7 8 9 10 11 | [{ label: '一级 2', children: [{ label: '二级 2-1', children: [{ label: '三级 2-1-1' }] }, { label: '二级 2-2' }] }] |
在ElementUI tree组件的区别就是,原数据’二级 2-2’可以展开一个空内容,而使用removeEmptyChildren 函数处理后,’二级 2-2’不可展开。这个其实也是一个用户体验的提升。
2020年4月29日 下午9:55
您好博主,互个友链可行
站点:唐子涵的个人博客
地址:http://www.zihanzy.com
已添加贵站