首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在javascript中使用相同键的对象结构递归结构

在javascript中使用相同键的对象结构递归结构
EN

Stack Overflow用户
提问于 2022-10-06 13:08:05
回答 1查看 59关注 0票数 -1

目前,我有一个对象

代码语言:javascript
复制
const path ={
    "posts": {
        "backend": {
            "a.mdx": "./pages/posts/backend/a.mdx"
        },
        "frontend": {},
        "retrospective": {
            "b.mdx": "./pages/posts/retrospective/b.mdx",
            "c.mdx": "./pages/posts/retrospective/c.mdx",
            "d.mdx": "./pages/posts/retrospective/d.mdx"
        }
    }
}

我想要的是。

代码语言:javascript
复制
  const path = [{
    title: 'posts',
    sub: [
      {
        title: 'backend',
        sub: [
          { title: 'a.mdx', path: './pages/posts/backend/a.mdx' },
        ],
      },
      {
        title: 'frontend',
        sub: [],
      },
      {
        title: 'retrospective',
        sub: [
          { title: 'b.mdx', path: './pages/posts/retrospective/b.mdx' },
          { title: 'c.mdx', path: './pages/posts/retrospective/c.mdx' },
          { title: 'd.mdx', path: './pages/posts/retrospective/d.mdx' },
        ],
      },
    ],
  }];

在这种情况下,如何使结构递归?我看过房客图书馆的文件,但我找不到一个很好的组合来处理这个问题。

能给我点提示吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-06 13:30:37

如果值是object,则可以创建递归函数并再次运行它;如果值是字符串,则可以设置path。检查内嵌注释:

代码语言:javascript
复制
// Object
const path = {
  "posts": {
    "backend": {
      "a.mdx": "./pages/posts/backend/a.mdx"
    },
    "frontend": {},
    "retrospective": {
      "b.mdx": "./pages/posts/retrospective/b.mdx",
      "c.mdx": "./pages/posts/retrospective/c.mdx",
      "d.mdx": "./pages/posts/retrospective/d.mdx"
    }
  }
};

// Recursive function
const recursiveFn = data => {
  // Set array for function runtime result
  const res = [];
  // Iterate through keys in your object
  for(const key in data) {
    // If value is object, process it
    // again in recursion
    if(typeof data[key] === 'object' && data[key] !== null) {
      res.push({
        "title": key,
        "sub": recursiveFn(data[key])
      });
    // If value is string
    } else if(typeof data[key] === 'string') {
      res.push({
        "title": key,
        "path": data[key]
      });
    }
  }
  // Return result
  return res;
}

// Run test
console.log(recursiveFn(path));

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73974374

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档