/* * @Description: 备份晨晨的代码 * @Autor: kindring * @Date: 2021-09-16 15:19:12 * @LastEditors: kindring * @LastEditTime: 2021-09-16 15:19:13 * @LastDescript: */ let input = { a: { b: "123", c: { d: 456, }, }, b: { e: 789, }, f: 222, }; const recursive = (tree, domain) => Object.entries(tree) .map(([key, value]) => [value, domain ? `${domain}.${key}` : key]) .map(([value, subDomain]) => typeof value === "object" ? recursive(value, subDomain) : subDomain ) .flat(); function depthFirst(tree) { const stack = [ [tree, ""] ]; const res = []; while (stack.length) { const [crt, crtPath] = stack.pop(); if (typeof crt === "object") { const entries = Object.entries(crt); let i = entries.length; while (i--) { const [key, value] = entries[i]; const path = crtPath ? `${crtPath}.${key}` : key; stack.push([value, path]); } } else { res.push(crtPath); } } return res; } function widthFirst(tree) { const queue = [ [tree, ""] ]; const res = []; while (queue.length) { const [crt, crtPath] = queue.shift(); if (typeof crt === "object") { const entries = Object.entries(crt); const last = entries.length - 1; let i = -1; while (i++ < last) { const [key, value] = entries[i]; const path = crtPath ? `${crtPath}.${key}` : key; queue.push([value, path]); } } else { res.push(crtPath); } } return res; } console.log(recursive(input)); console.log(depthFirst(input)); console.log(widthFirst(input));