Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive function with an Object in JS

I have an array that contains objects that might have nth levels of depth.

Something like this:

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'}  

        ]}  
    ]}

]

I need to push on a different array only the 'Url' property and the children property if present, preserving the depth though.

So the new array should look like this:

const newArray = [

    {url: '/pictures'},
    {url: '/user/:username', children:[
        {url: '/user/:username/highlights', children:[
                {url: '/user/:username/highlights'} 
        ]}  
    ]}

]

Can you help me?

Thanks

like image 318
rolfo85 Avatar asked Aug 28 '26 05:08

rolfo85


1 Answers

You could use a destructuring assignment for the wanted keys and use Array#map for getting a new array with only the one property and use Object.assign for the children objects by checking the children and if exist, take the urls from the children with a recursive call of the function.

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; }
like image 116
Nina Scholz Avatar answered Aug 29 '26 18:08

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!