postman 基于特定值解析多数组JSON对象

jjjwad0x  于 2023-02-04  发布在  Postman
关注(0)|答案(3)|浏览(210)

我需要从一个有多个数组的JSON对象中获取一些guid。我需要一些guid,但不是全部。我用Javascript做这个是为了一个 Postman 测试。
具体地说,我需要从user. roles. org. guidMap出一个新的数组,仅用于user. roles. role为"teacher"的guid。
JSON示例:

{
    "user": {
        "guid": "foobar",
        "status": "foobar",
        "dateLastModified": "foobar",
        "username": "foobar",
        "enabledUser": "foobar",
        "givenName": "foobar",
        "familyName": "foobar",
        "middleName": "foobar",
        "email": "foobar",
        "sms": "foobar",
        "roles": [
            {
                "beginDate": "foobar",
                "roleType": "foobar",
                "role": "teacher",
                "org": {
                    "href": "foobar",
                    "guid": "5C354F4D-DFD0-406D-8B83-7D5C8B64EF8B",
                    "type": "org"
                }
            },
            {
                "beginDate": "foobar",
                "roleType": "foobar",
                "role": "teacher",
                "org": {
                    "href": "foobar",
                    "guid": "E2FECF7B-DA7B-4534-B467-337DEA01118C",
                    "type": "org"
                }
            },
            {
                "beginDate": "foobar",
                "roleType": "foobar",
                "role": "aide",
                "org": {
                    "href": "foobar",
                    "guid": "E2F2B7C5-37A1-4D6C-8BB8-64E45CF71030",
                    "type": "org"
                }
            }
        ],
         "grades": [
            "12",
            "12"
        ]
    }
}

我已经在user.roles.org.guid下为 * all * guid创建了一个新数组:

var data = JSON.parse(responseBody)
var objectType = (data.user)
var guids = objectType.roles.org.map(guids => guids.guid)

......但我不知道该如何把它限制在教师的角色上。谢谢!

sg24os4d

sg24os4d1#

为此,您需要filter(),然后map()过滤结果。

let data = JSON.parse(responseBody);
let teacherGuids = data.user.roles
  .filter(role => role.role === "teacher")
  .map(teacherRole => teacherRole.org.guid);
vqlkdk9b

vqlkdk9b2#

data.user.roles.filter((e)=>{return e.role == "teacher"}).map((e)=>{return e.org.guid});
dsf9zpds

dsf9zpds3#

要只获取角色为“教师”的guid,可以在objectType.roles上使用filter函数获取所有角色为“教师”的guid,然后在过滤后的数组上使用map函数获取guid:

var data = JSON.parse(responseBody)
var objectType = (data.user)
var teacherRoles = objectType.roles.filter(role => role.role === "teacher")
var guids = teacherRoles.map(teacherRole => teacherRole.org.guid)

相关问题