【问题标题】:JavaScript how filter nested object's arrayJavaScript如何过滤嵌套对象的数组
【发布时间】:2019-07-10 04:59:50
【问题描述】:

我有这个数组。

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 实现这一点?

【问题讨论】:

标签: javascript


【解决方案1】:

对于这些数组操作之王,我很好地减少是更好的方法。

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-05-09
    • 2020-02-01
    • 2021-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多