鍍金池/ 問答/Java  HTML/ json取值

json取值

clipboard.png

在不確定層級關(guān)系的情況下 這種數(shù)據(jù)格式 我怎么能夠取到 isLeaf:?true 的這個label
可以知道它的value

回答
編輯回答
孤巷

不知道關(guān)系?那只有遍歷了。。。

2017年11月22日 22:01
編輯回答
網(wǎng)妓

看這個數(shù)據(jù),葉節(jié)點應(yīng)該不少。如果不允許非空父節(jié)點的話,每個看得見的父節(jié)點下至少會有一個葉節(jié)點。所以你是要找第一個葉節(jié)點呢,還是要找所有葉節(jié)點呢?

這里提供一個找所有葉節(jié)點的方法,沒用遞歸,用的廣度遍歷(相關(guān)閱讀:使用遞歸遍歷并轉(zhuǎn)換樹形數(shù)據(jù),這里面也講了廣度)。這里采用 ES2015 的 generator 語法實現(xiàn)

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())
        // 這里就已經(jīng)取到了所有的葉節(jié)點
        .filter(node => !node.isLeaf)
        // 這里進一步取到了所有葉節(jié)點的 value 值,
        // 反正節(jié)點都在,想要什么值都可以取得到了
        .map(node => node.value);
}
2017年5月21日 09:17
編輯回答
夏夕

這不就是樹的遍歷嗎。。。
簡單寫個遞歸就可以了

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
}
2017年1月20日 10:30
編輯回答
影魅

遞歸遍歷,判斷isLeaf是否為true

2017年8月11日 22:07