[英]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.