David
David

Reputation: 41

Parse JSON object with multiple arrays based on specific value

I need to grab some guids out of a JSON object that has multiple arrays. I need some of the guids, but not all of them. I'm doing this in Javascript for a Postman test.

Specifically, I need to map a new array out of user.roles.org.guid, only for the guids where the user.roles.role is "teacher".

Example 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"
        ]
    }
}

I have gotten as far as creating a new array for all guids under user.roles.org.guid:

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

...but I'm not sure how to limit that to just a role of teacher. Thanks!

Upvotes: 0

Views: 545

Answers (2)

Fra
Fra

Reputation: 11

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

Upvotes: 1

Kevinazoulay
Kevinazoulay

Reputation: 74

To do so you need to filter() and then map() your filtered result.

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

Upvotes: 2

Related Questions