javascript - JS中带有对象的递归函数
问题描述
我有一个数组,其中包含可能具有第 n 级深度的对象。
像这样的东西:
const settings = [
{path: '/templates/pictures.php', url: '/pictures', label: 'Pictures', component: 'tab', template: 'default'},
{path: '/templates/post-article.php', url: '/user/:username', component: 'table', template: 'default', children:[
{path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default', children:[
{path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default'}
]}
]}
]
我只需要在不同的数组上推送 'Url' 属性和 children 属性(如果存在),但保留深度。
所以新的数组应该是这样的:
const newArray = [
{url: '/pictures'},
{url: '/user/:username', children:[
{url: '/user/:username/highlights', children:[
{url: '/user/:username/highlights'}
]}
]}
]
你能帮助我吗?
谢谢
解决方案
您可以对想要的键使用解构赋值Array#map
,并用于获取只有一个属性的新数组,并Object.assign
通过检查子对象来使用子对象,如果存在,则通过函数的递归调用从子对象中获取 url。
function getUrls(array) {
return array.map(({ url, children }) =>
Object.assign({ url }, children && { children: getUrls(children) }));
}
var settings = [{ path: '/templates/pictures.php', url: '/pictures', label: 'Pictures', component: 'tab', template: 'default' }, { path: '/templates/post-article.php', url: '/user/:username', component: 'table', template: 'default', children: [{ path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default', children: [{ path: '/templates/post-article-highlights.php', url: '/user/:username/highlights', component: 'table', template: 'default' }] }] }],
urls = getUrls(settings);
console.log(urls);
.as-console-wrapper { max-height: 100% !important; top: 0; }
推荐阅读
- for-loop - char *、内存地址、ASCII码之间有什么关系?
- java - 在 Hi-Lo 游戏中找到最少猜测次数的问题
- swift - 如何从应用程序将缓冲区发送到 DAL 插件
- python - Pandas 自定义 Cumcount
- javascript - Sweetalert 组件没有在使用 javascript 的循环内触发
- javascript - Javascript解析已按顺序完成的承诺数组中的第一个元素
- asp.net - Azure Pipelines 生成后事件复制命令失败
- amazon-s3 - 创建具有多个 s3 路径的 aws 胶水爬虫
- c++ - 为整数指定无符号字符存储
- javascript - 对象数组中的未定义值Vuejs