Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.3k views
in Technique[技术] by (71.8m points)

树形结构数据如何删除空的子级节点?

我有这样一组数据,想要递归删除掉所有 children 为空的节点,对于这组数据来说,最后删除完后,会得到空数据。

但是我设计的方法好像行不通,请大家帮忙给我个思路,或者说帮忙指出我这段程序中有什么错误的地方,不胜感激:

数据

data = [
    {id: 1, label: '1-1', children: 
        [
            {id: 2, label: '1-2', children: []},
            {id: 3, label: '1-3', children: []},
        ]
    },
    {id: 4, label: '2-1', children: []},
];

尝试的方法

function getSelectedNode(nodeData, parent) {
  nodeData.forEach(item => {
    if ('children' in item && item.children.length === 0) {
      // 使用了lodash的删除方法
      lodash.remove(parent.children, o => {
        return o.id === item.id
      })
    } else if ('children' in item && item.children.length) {
      getSelectedNode(item.children, item);
    }
  })
}
getSelectedNode(data, data);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

既然已经遍历到了,为什么不直接删掉呢?

function getSelectedNode(nodeData, parent) {
  nodeData.forEach(item => {
    if ('children' in item && item.children.length === 0) {
      delete item.children
    } else if ('children' in item && item.children.length) {
      getSelectedNode(item.children, item);
    }
  })
}
getSelectedNode(data, data);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...