Home > Mobile >  make object structure recursive structure with same keys in javascript
make object structure recursive structure with same keys in javascript

Time:10-07

Currently, I have this 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"
        }
    }
}

What I want is..

  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' },
        ],
      },
    ],
  }];

In this situation, how can I make the structure recursively? I've read the lodash library document but I couldn't find a good combination to handle this issue.

Can I get any hint for this?

CodePudding user response:

You can create recursive function and run it again if value is object, or set path if it is string. Check inline comments:

// 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));

  • Related