如何将一组路由配置对象合并到一个已清除配置的数组中?

时间:2019-02-21 18:18:26

标签: javascript arrays sorting math ecmascript-6

我们将路由配置存储在node_modules

的多个包中

当我们将其全部分组到应用程序中的一个数组中时,我们希望根据path对其进行正确排序。

对于childRoutes可识别的孩子,我们希望保留深度。

它是这样的:

const routeConfig1 = [
  {
    path: "/user-management",
    childRoutes: [
      {
        path: "/user-management/user",
        childRoutes: [
          {
            path: "/user-management/user/service"
          }
        ]
      }
    ]
  }
];

const routeConfig2 = [
  {
    path: "/user-management",
    childRoutes: [
      {
        path: "/user-management/user",
        component: "UserComponent",
        childRoutes: [
          {
            path: "/user-management/user/service/tokyo",
            component: "TokyoService"
          }
        ]
      }
    ]
  }
];

const routeConfig3 = [
  {
    path: "/user-management",
    childRoutes: [
      {
        path: "/user-management/user/:id"
      }
    ]
  }
];

const routeConfigList = [routeConfig1, routeConfig2, routeConfig3];

function mergeRouteConfig(list) {
  let newList = [...list];
  list.map(r => {});
  return newList;
}

const flatten = mergeRouteConfig(routeConfigList);

const expected = [
  [
    {
      path: "/user-management",
      childRoutes: [
        {
          path: "/user-management/user",
          component: "UserComponent",
          childRoutes: [
            {
              path: "/user-management/user/service"
            },
            {
              path: "/user-management/user/service/tokyo",
              component: "TokyoService"
            }
          ]
        },
        {
          path: "/user-management/user/:id"
        }
      ]
    }
  ]
];

const flattenStr = JSON.stringify(flatten, null, 2);
const expectedStr = JSON.stringify(expected, null, 2);
const result = flattenStr === expectedStr;

document.getElementById(
  "app"
).innerHTML = `<h2>Result: ${`<span style="color: ${
  result ? "green" : "red"
}">${result ? "OK" : "NOK"}</span>`}</h2>
<pre>
${flattenStr}
</pre>
<h2>Expected</h2>
<pre>
${expectedStr}
</pre>
`;
body{font-family:sans-serif}pre{background:#ccc}
<div id="app"></div>

代码和框https://codesandbox.io/s/1zmy69r5mq

我尝试过使用Mapreduce,但是我的代码看起来有些复杂,如何正确实现呢?

0 个答案:

没有答案