首页 > 解决方案 > 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'} 
        ]}  
    ]}

]

你能帮助我吗?

谢谢

标签: javascriptarraysobjectrecursion

解决方案


您可以对想要的键使用解构赋值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; }


推荐阅读