Skip to content

Instantly share code, notes, and snippets.

@sonnyksimon
Last active March 13, 2020 17:48
Show Gist options
  • Save sonnyksimon/ba9b2e17f48ffbbe32b41531ffc67692 to your computer and use it in GitHub Desktop.
Save sonnyksimon/ba9b2e17f48ffbbe32b41531ffc67692 to your computer and use it in GitHub Desktop.
Reduce a list of users and a list of roles for each user into a single unified listing of users.
const data = JSON.parse(`{
"users": [
{
"id": 1,
"name": "basicuser"
},
{
"id": 2,
"name": "adminuser"
}
],
"userroles": [
{
"id": 7,
"user_id": 1,
"role": "BASIC"
},
{
"id": 8,
"user_id": 2,
"role": "ADMIN"
}
]
}`)
let users = []
data.users.forEach(u => {
users.push({roles: data.userroles.filter( r =>
r.user_id === u.id
).map(
r => r.role
), ...u})
})
console.log(users)
import json
data = json.loads("""{
"users": [
{
"id": 1,
"name": "basicuser"
},
{
"id": 2,
"name": "adminuser"
}
],
"userroles": [
{
"id": 7,
"user_id": 1,
"role": "BASIC"
},
{
"id": 8,
"user_id": 2,
"role": "ADMIN"
}
]
}""")
users = []
for u in data['users']:
users.append(dict(roles=list(map(lambda r: r['role'], filter(lambda r: r['user_id'] == u['id'], data['userroles']))), **u))
print(users)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment