Skip to content
Advertisement

Filter children in nested object

I have an object which I’m trying to filter out elements with a path and map, but I can’t get past the first level into the nested children.

My object (with UI components removed):

  const items = [
    {
      path: "/login"
    },
    {
      path: "/help"
    },
    {
      name: "Guidelines",
      children: [
        {
          name: "Section 1",
          children: [
            {
              name: "Chapter 1",
              path: "/section-1/chapter-1"
            },
            {
              name: "Chapter 2",
              path: "/section-1/chapter-2"
            }
          ]
        },
        {
          name: "Section 2",
          children: [
            {
              name: "Chapter 3",
              path: "/section-2/chapter-3"
            },
            {
              name: "Chapter 4",
              path: "/section-2/chapter-4"
            }
          ]
        }
      ]
    }
  ];

This filters the elements with a path, but only to the first level:

const filteredRoutes = items.filter((route) => route.path);

Result:

[
 {"path":"/login"},
 {"path":"/help"}
]

My goal is to have a list of routes with 6 items in this Codesandbox

[
  { "path": "/login" },
  { "path": "/help" },
  { "path": "/section-1/chapter-1" },
  { "path": "/section-1/chapter-2" },
  { "path": "/section-2/chapter-3" },
  { "path": "/section-2/chapter-4" },
]

Thanks

Advertisement

Answer

const getPath = (x) => (x.path ? { path: x.path } : x.children?.map(getPath));
const filteredRoutes = items && items.map(getPath).flat(Infinity);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement