function traverseDf(data, callback) { (function recurse(currentNode) { if(currentNode.children) { for(let item of currentNode.children) { recurse(item); } } callback(currentNode); })(data); } // 廣度優先 function traverseBf(data, callback) { const queue = []; queue.push(data); let currentTree = queue.shift(); while(currentTree){ if(currentTree.children) { for(const item of currentTree.children) { queue.push(item); } } callback(currentTree); currentTree = queue.shift(); } } // 獲取樹中某個key的全部value function getArray(data, key) { const vals = []; const cb = function cb(node) { if(node[key]) { vals.push(node[key]); } } traverseBf(data, cb); return vals } // 給樹中節點添加屬性 function addPropToTree(data, key, callback) { const cb = function cb(node) { node[key] = callback(node); } traverseBf(data, cb); return data; }