簡體   English   中英

JavaScript 如何過濾嵌套對象的數組

[英]JavaScript how filter nested object's array

我有這個數組。

 const items = [ { text: "Dashboard", roles: ["manager", "staff"] }, { text: "User management", roles: ["admin", "manager", "staff"], children: [ { text: "Create Suburb", roles: ["manager", "admin"] }, { text: "View and Update Suburb", roles: ["staff"] }, { text: "Create shoping mall" } ] } ];

我想在根對象和子數組的對象中過濾這個角色名稱。

如果我將staff作為我的參數傳遞,我的預期輸出是這樣的

 const items = [ { text: "Dashboard", roles: ["manager", "staff"] }, { text: "User management", roles: ["admin", "manager", "staff"], children: [ { text: "View and Update Suburb", roles: ["staff"] } ] } ];

我現在所做的是

const data = items.filter(element => {
  return element.roles.includes("staff");
});

這基本上過濾了根對象。 但不過濾嵌套的子數組對象。 我如何使用 JS 實現這一目標?

嘗試使用遞歸(如果children也有children就很好用)

 const items = [ { text: "Dashboard", roles: ["manager", "staff"] }, { text: "User management", roles: ["admin", "manager", "staff"], children: [ { text: "Create Suburb", roles: ["manager", "admin"] }, { text: "View and Update Suburb", roles: ["staff"] }, { text: "Create shoping mall" } ] } ]; // recursive filter function filter(group, role){ return group.filter(item => { if(item.children){ item.children = filter(item.children, role) } return item.roles && item.roles.includes(role); }); } const data = filter(items, 'staff'); console.log(data); 

對於這些數組操作之王,我精簡減少是更好的方法。

 const items = [ { text: 'Dashboard', roles: ['manager', 'staff'] }, { text: 'User management', roles: ['admin', 'manager', 'staff'], children: [ { text: 'Create Suburb', roles: ['manager', 'admin'] }, { text: 'View and Update Suburb', roles: ['staff'] }, { text: 'Create shoping mall' } ] } ] function filterWithRoles(data,role) { return items.reduce((acc, item) => { if (item.roles.includes(role)) { item.children = item.children && item.children.filter(child => child.roles && child.roles.includes(role)) acc.push(item) } return acc }, []) } console.log(JSON.stringify(filterWithRoles(items,'staff'), null, 2)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM