[英]JS filter some part from an array of objects
我有這個數組。
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"
}
]
},
]
請注意,兩個對象被完全刪除,第三個 object 的某些部分也被刪除。 我如何使用 JS 實現這一點?
我到目前為止所做的是這個
items.filter(e=>{
if(e.path){
return permissions.includes(e.path)
}else{
}
})
希望我的問題對你來說很清楚。
您可以使用 reduce 來做到這一點 - 單獨的過濾器在這里不起作用,因為您實際上是在轉換子 arrays 而不是純粹過濾頂級數組項
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;
}, []);
嘗試這個!!
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']; let result = []; permissions.map(permission=>{ routes.map(route=>{ if(route.hasOwnProperty('children')){ route.children.map((r,i)=>{ if(r.path == permission){ route.children = route.children.splice(i); route.children = route.children.slice(-1); result.push(route) } }); }else{ if(route.path == permission){ result.push(route) } } }); }) console.log(result)
這個也對我有用。
var newData = [];
$.each(routes, function (key, value) {
debugger
var data = this;
if (data.path) {
if (permissions.includes(data.path)) {
newData.push(data);
}
}
else {
var data2 = data;
$.each(data2, function (key, value1) {
$.each(value1, function (key, value) {
var data = value;
if (data.path) {
if (permissions.includes(data.path)) {
newData.push(data);
}
}
});
});
}
})
其實你是在正確的道路上。 解決問題的方法需要稍作修改,您已經編寫的代碼將為您提供所需的結果。
仔細觀察:您的孩子在 routes 數組中是 roue 本身的復制品。
所以,你需要做的是:
希望這個算法有意義,如果您需要任何代碼幫助,請告訴我。
理想情況下,您應該檢查對 canActivate 守衛內路由的訪問,並將用戶進一步導航到適當的路由。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.