简体   繁体   English

JavaScript 如何过滤嵌套对象的数组

[英]JavaScript how filter nested object's array

I've this 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" } ] } ];

I want to filter this the role name both in the root objects and children array's objects.我想在根对象和子数组的对象中过滤这个角色名称。

If I pass the staff as my parameter, my expected output is this如果我将staff作为我的参数传递,我的预期输出是这样的

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

What I did upto now is我现在所做的是

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

This basically filter the root objects.这基本上过滤了根对象。 But not filter the nested children array's object.但不过滤嵌套的子数组对象。 How do I achieve this using JS?我如何使用 JS 实现这一目标?

Try using recursion(works fine if children also has children ) 尝试使用递归(如果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); 

For these king of array manipulations I fine reduce is the better way. 对于这些数组操作之王,我精简减少是更好的方法。

 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