晨晨每日js.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * @Description: 备份晨晨的代码
  3. * @Autor: kindring
  4. * @Date: 2021-09-16 15:19:12
  5. * @LastEditors: kindring
  6. * @LastEditTime: 2021-09-16 15:19:13
  7. * @LastDescript:
  8. */
  9. let input = {
  10. a: {
  11. b: "123",
  12. c: {
  13. d: 456,
  14. },
  15. },
  16. b: {
  17. e: 789,
  18. },
  19. f: 222,
  20. };
  21. const recursive = (tree, domain) =>
  22. Object.entries(tree)
  23. .map(([key, value]) => [value, domain ? `${domain}.${key}` : key])
  24. .map(([value, subDomain]) =>
  25. typeof value === "object" ? recursive(value, subDomain) : subDomain
  26. )
  27. .flat();
  28. function depthFirst(tree) {
  29. const stack = [
  30. [tree, ""]
  31. ];
  32. const res = [];
  33. while (stack.length) {
  34. const [crt, crtPath] = stack.pop();
  35. if (typeof crt === "object") {
  36. const entries = Object.entries(crt);
  37. let i = entries.length;
  38. while (i--) {
  39. const [key, value] = entries[i];
  40. const path = crtPath ? `${crtPath}.${key}` : key;
  41. stack.push([value, path]);
  42. }
  43. } else {
  44. res.push(crtPath);
  45. }
  46. }
  47. return res;
  48. }
  49. function widthFirst(tree) {
  50. const queue = [
  51. [tree, ""]
  52. ];
  53. const res = [];
  54. while (queue.length) {
  55. const [crt, crtPath] = queue.shift();
  56. if (typeof crt === "object") {
  57. const entries = Object.entries(crt);
  58. const last = entries.length - 1;
  59. let i = -1;
  60. while (i++ < last) {
  61. const [key, value] = entries[i];
  62. const path = crtPath ? `${crtPath}.${key}` : key;
  63. queue.push([value, path]);
  64. }
  65. } else {
  66. res.push(crtPath);
  67. }
  68. }
  69. return res;
  70. }
  71. console.log(recursive(input));
  72. console.log(depthFirst(input));
  73. console.log(widthFirst(input));