gpt4 book ai didi

javascript - JS中带有对象的递归函数

转载 作者:行者123 更新时间:2023-11-29 10:29:22 24 4
gpt4 key购买 nike

我有一个数组,其中包含可能具有第 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”属性和子属性(如果存在)推送到另一个数组,但要保留深度。

所以新数组应该是这样的:

const newArray = [

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

]

你能帮帮我吗?

谢谢

最佳答案

你可以使用 destructuring assignment对于想要的键并使用 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; }

关于javascript - JS中带有对象的递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50191952/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com