0

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!

1
  • Use filter() to select only the roles where role.role == 'teacher' Commented Feb 3, 2023 at 21:07

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

A one line answer with no commentary/links is not a great answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.