需要帮助将ReactJS TypeScript中的嵌套数组对象(2级)转换为数组对象(1级)



当尝试提取2级嵌套对象数组到1级对象数组时,我遇到了一个问题。我使用React和TypeScript。这是我的源数组:

const sidebar = [
{
label: "label 1",
children: [
{
label: "label 1.1",
path: "/setting/roles",
icon: "icon 1.1",
},
{
label: "label 1.2",
path: "/setting/employees",
icon: "icon 1.2",
},
],
},
{
label: "label 2",
path: "'/setting/departments'",
icon: "icon 2",
},
];

及以下是我期望的数组:

const sidebarExpected = [
{
label: "label 1.1",
path: "/setting/roles",
icon: "icon 1.1",
},
{
label: "label 1.2",
path: "/setting/employees",
icon: "icon 1.2",
},
{
label: "label 2",
path: "'/setting/departments'",
icon: "icon 2",
},
];

我使用Yarn,更喜欢不需要安装新包的解决方案(但如果没有任何方法,使用新包的解决方案也可以,例如lodash)。下面是我的包裹。json文件:

{
"name": "product-hrm",
"version": "0.0.0",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"lint": "run-p -l lint:*",
"lint:es": "eslint src/** --ext .ts,.tsx --no-error-on-unmatched-pattern",
"lint:prettier": "prettier --config .prettierrc.json --write '**/*.tsx'"
},
"dependencies": {
"@emotion/react": "^11.7.1",
"@emotion/styled": "^11.6.0",
"@hookform/resolvers": "^2.8.5",
"@mui/icons-material": "^5.2.5",
"@mui/joy": "^5.0.0-alpha.32",
"@mui/lab": "^5.0.0-alpha.87",
"@mui/material": "^5.2.6",
"@mui/styles": "^5.2.3",
"axios": "^0.24.0",
"countries-and-timezones": "^3.3.0",
"date-fns": "^2.28.0",
"history": "5",
"i18next": "^21.6.16",
"i18next-http-backend": "^1.4.0",
"jotai": "^1.4.9",
"pusher-js": "^7.0.6",
"react": "^17.0.2",
"react-bottom-scroll-listener": "^5.0.0",
"react-dom": "^17.0.2",
"react-drag-drop-files": "^2.3.7",
"react-dropzone": "^12.0.2",
"react-hook-form": "^7.22.5",
"react-i18next": "^11.16.7",
"react-mui-dropzone": "^4.0.6",
"react-query": "^3.34.7",
"react-router-dom": "^6.2.1",
"react-table": "^7.7.0",
"react-toastify": "^9.0.1",
"xlsx": "^0.18.0",
"yup": "^0.32.11"
},
"devDependencies": {
"@honkhonk/vite-plugin-svgr": "^1.1.0",
"@types/react": "^17.0.33",
"@types/react-dom": "^17.0.10",
"@types/react-table": "^7.7.9",
"@typescript-eslint/eslint-plugin": "^5.8.1",
"@typescript-eslint/parser": "^5.8.1",
"@vitejs/plugin-legacy": "^1.6.4",
"@vitejs/plugin-react": "^1.0.7",
"eslint": "^8.5.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-jsx-a11y": "^6.5.1",
"eslint-plugin-prettier": "^4.0.0",
"eslint-plugin-react": "^7.28.0",
"eslint-plugin-react-hooks": "^4.3.0",
"prettier": "^2.5.1",
"prettier-plugin-organize-imports": "^2.3.4",
"typescript": "^4.4.4",
"vite": "^2.7.2",
"vite-plugin-components": "^0.13.3",
"vite-tsconfig-paths": "^3.3.17"
}
}

无论它有多少层,这个方法都将使它变平。

这是一个递归解。只要你有孩子,它就会召唤那些孩子。flatten参数被初始化为一个空数组,但在递归调用时,它将被更新为没有子节点的节点(因为它推送的else)——将参数传递给函数将受益于尾部递归函数(如果尾部调用优化由浏览器实现)

const flat = (array, flatten = []) => {
for (let i = 0; i < array.length; i ++) {
if (array[i].children) {
flat(array[i].children, flatten);
} else {
flatten.push(array[i]);
}
}
return flatten;
}

最新更新