json取值

clipboard.png

在不确定层级关系的情况下 这种数据格式 我怎么能够取到 isLeaf: true 的这个label
可以知道它的value

阅读 3.4k
4 个回答

看这个数据,叶节点应该不少。如果不允许非空父节点的话,每个看得见的父节点下至少会有一个叶节点。所以你是要找第一个叶节点呢,还是要找所有叶节点呢?

这里提供一个找所有叶节点的方法,没用递归,用的广度遍历(相关阅读:使用递归遍历并转换树形数据,这里面也讲了广度)。这里采用 ES2015 的 generator 语法实现

function findLeaves(roots) {
    const queue = [...roots];

    function* next() {
        while (true) {
            const node = queue.shift();
            if (!node) {
                return;
            }

            if (node.children && node.children.length) {
                queue.push(...node.children);
            }
            yield node;
        }
    }

    return Array.from(next())
        // 这里就已经取到了所有的叶节点
        .filter(node => !node.isLeaf)
        // 这里进一步取到了所有叶节点的 value 值,
        // 反正节点都在,想要什么值都可以取得到了
        .map(node => node.value);
}

不知道关系?那只有遍历了。。。

递归遍历,判断isLeaf是否为true

这不就是树的遍历吗。。。
简单写个递归就可以了

function getLeafLabel(tree) {
    return tree.isLeaf
        ? tree.label
        : getInChildren(tree)
}
function getInChildren(tree) {
    let result
    tree.children && tree.children.forEach(tree => {
      result = result || getLeafLabel(tree)
    })
    return result
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题