簡體   English   中英

使用 lodash 展平嵌套對象/數組

[英]Flatten nested object/array using lodash

是否可以使用 lodash 來展平這個集合並連接路徑字符串? 我試圖但只能達到第二級,只要對象中有一個 pageRouter 數組,我就想將它展平而不管深度如何

{
    component: () => React.createElement('div', undefined, 'Parent Page'),
    exact: true,
    pageTitle: 'Parent',
    path: '/parent',
    pageRoute: [
      {
        component: () => React.createElement('div', undefined, 'Child Page'),
        exact: true,
        pageTitle: 'Child',
        path: '/child',
        pageRoute: [
          {
            component: () =>
              React.createElement('div', undefined, 'Grandchild Page'),
            exact: true,
            pageTitle: 'GrandChild',
            path: '/grandchild',
          },
        ],
      },
    ],
  },

到這個?

 [
    {
      component: () => React.createElement('div', undefined, 'Parent Page'),
      exact: true,
      pageTitle: 'Parent',
      path: '/parent',
    },
    {
      component: () => React.createElement('div', undefined, 'Child Page'),
      exact: true,
      pageTitle: 'Child',
      path: '/parent/child',
    },
    {
      component: () => React.createElement('div', undefined, 'Grandchild Page'),
      exact: true,
      pageTitle: 'GrandChild',
      path: 'parent/child/grandchild',
    },
  ],

嘗試的代碼

const = routeList = _.flatMapDeep(publicRoutes, (x) => {
   if (x.pageRoute) {
      return [x, { ...x.pageRoute, path: x.path + _.head(x.pageRoute)?.path }];
     } else return x;
   });

不需要lodash 由於這是一個嵌套結構,因此對於遞歸函數來說似乎是一個好機會:

 const components = [ { component: () => React.createElement('div', undefined, 'Parent Page'), exact: true, pageTitle: 'Parent', path: '/parent', pageRoute: [ { component: () => React.createElement('div', undefined, 'Child Page'), exact: true, pageTitle: 'Child', path: '/child', pageRoute: [ { component: () => React.createElement('div', undefined, 'Grandchild Page'), exact: true, pageTitle: 'GrandChild', path: '/grandchild', }, ], }, ], } ]; const flattenedComponents = [...flattenComponents(components, '')]; console.log(flattenedComponents); function* flattenComponents(nestedComponents, pathPrefix) { for (const { pageRoute: routes, path, ...component } of nestedComponents) { const newPath = `${pathPrefix}${path}`; yield { ...component, path: newPath }; if (routes) { yield* flattenComponents(routes, newPath); } } }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM