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!
CodePudding user response:
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);
CodePudding user response:
data.user.roles.filter((e)=>{return e.role == "teacher"}).map((e)=>{return e.org.guid});
CodePudding user response:
To only get the guids where the role is "teacher", you can use filter function on objectType.roles to get all roles that are "teacher", then use map function on the filtered array to get the 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)