首页 > 解决方案 > 如何正确过滤 JavaScript 中的对象?

问题描述

我正在关闭权限 ID 并尝试过滤具有这些权限的对象。这是 JSON 对象的简洁版本

[
  {
    "id": "INS-SH-V",
    "name": "View Sharing Functionality",
    "description": "Access to view Email and Schedule windows",
    "group": "Sharing",
    "scopeable": false,
    "featureId": "INS-BE",
    "scopeExclusions": null,
    "dependsOn": null
  },
  {
    "id": "INS-SH-U",
    "name": "Manage Sharing Functionality",
    "description": "Access to send emails and schedule jobs",
    "group": "Sharing",
    "scopeable": false,
    "featureId": "INS-BE",
    "scopeExclusions": null,
    "dependsOn": [
      "INS-SH-V"
    ]
  }
 ]

基本上我被给定INS-SH-V并且想要扫描每个dependsOn属性中的所有项目,如果INS-SH-V有那么我想返回id那个对象的。有没有一种简单的方法可以做到这一点?我一直在努力让它在 for 循环中工作。

谢谢!

到目前为止,这是我的尝试:

let len = this.props.permissions.length;
    for (let i = 0; i < len; i++){
      if (this.props.permissions[i].dependsOn[0] !== null){
        // return this.props.permissions[i].id // Should return INS-SH-U
        if (permissionId === this.props.permissions[i].dependsOn[0]){
          // return this.props.permissions[i].id
          console.log(this.props.permissions[i].id);
        }
      }
    }
    return null;

标签: javascriptreactjs

解决方案


您可以使用filter来过滤您的数组,然后使用 map 仅获取 id:

编辑:添加包括

const checkId = 'SOME ID'
const ids = yourData.filter(obj => obj['dependsOn'] !== null && obj['dependsOn'].includes(checkId)).map(obj => obj.id)

推荐阅读