gpt4 book ai didi

javascript - JS 从对象数组中过滤某些部分

转载 作者:行者123 更新时间:2023-12-02 22:46:39 25 4
gpt4 key购买 nike

我有这个数组。

const routes = [
{
path:'/dashboard',
text: "Dashboard"
},
{
path:'/disputes',
text: "Disputes"
},
{
children: [
{
text: "Create Suburb",
path: "/create-suburb"
},
{
text: "View and Update Suburb",
path: "/view-suburb"
}
]
},
{
children: [
{
text: "Create user",
path: "/create-user"
},
{
text: "View and Update users",
path: "/view-users"
}
]
}

]

我有这个数组

const permissions = ['/dashboard','/view-suburb'];

我想要的是从数组中过滤掉 permissions 数组中没有的对象。

我的预期输出是这样的

const routes = [
{
path:'/dashboard',
text: "Dashboard"
},

{
children: [
{
text: "View and Update Suburb",
path: "/view-suburb"
}
]
},

]

请注意,两个对象被完全删除,第三个对象的某些部分也被删除。如何使用 JS 实现此目的?

到目前为止我所做的就是这样

items.filter(e=>{
if(e.path){
return permissions.includes(e.path)
}else{

}
})

希望您能清楚我的问题。

最佳答案

您可以使用reduce来做到这一点 - 单独的过滤器在这里不起作用,因为您实际上是在转换子数组而不是纯粹过滤顶级数组项


routes.reduce((result, route) => {
const { path, children } = route;
if (children) {
const filteredChildren = children.filter(child => permissions.includes(child.path));

// case where some child routes match permissions
if (filteredChildren.length !== 0) {
return [ ...result, { ...route, children: filteredChildren }];
}
}

// case where path is present and permissions includes path
if (path && permissions.includes(path)) {
return [ ...result, route ];
}

// case where there's no match between path and permissions
return result;
}, []);

关于javascript - JS 从对象数组中过滤某些部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58376632/

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