javascript - 如何正确过滤 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;
解决方案
您可以使用filter
来过滤您的数组,然后使用 map 仅获取 id:
编辑:添加包括
const checkId = 'SOME ID'
const ids = yourData.filter(obj => obj['dependsOn'] !== null && obj['dependsOn'].includes(checkId)).map(obj => obj.id)
推荐阅读
- swift - iOS 上的 Firebase - 下载 GoogleService-Info.plist
- javascript - Javascript 音频无法在移动设备上运行
- php - 如何让单选按钮记住用户在 edit.blade.php laravel 中给出的上一个选项
- java - 我应该使用什么进口
- python - 在 numba 中编译 abs() 比普通的 python 函数慢
- r - 更新此数据时自动更新数据文档
- reactjs - 刷新浏览器时反应路由器不起作用
- javascript - 带有对象 Javascript 或 JSON 的列自定义数据表
- kotlin - 从 Firebase 存储中获取图像。GlideApp 未解决的参考
- android - 如何将服务添加到设置菜单?