【发布时间】:2018-07-04 19:32:03
【问题描述】:
我最近开始使用 Ramda 来处理来自 JSONAPI 的响应。我在处理复杂的关系和想办法从多个对象中获取我想要的数据时遇到了一些麻烦。
一个用户被分配给一个user_role,它被分配给一个角色。一个角色可以有多个 user_role,但一个 user_role 只能分配给一个角色。一个用户可以有多个 user_role,但为了简单起见,我只为每个用户分配了一个 user_role。
我的目标是获取 user_role 中引用的角色并将其放置在用户对象中的新“包含”对象中。
例如:
取这三组数据,用户,user_roles,角色:
const users = [
{
id: 1,
attributes: {
firstName: "Bob",
lastName: "Lee"
},
relationships: {
user_roles: {
data: {
id: 1,
type: "user_roles"
}
}
},
type: "users"
},
{
id: 2,
attributes: {
firstName: "Kevin",
lastName: "Smith"
},
relationships: {
user_role: {
data: {
id: 2,
type: "user_roles"
}
}
},
type: "users"
},
];
const user_roles = [
{
id: 1,
attributes: {
createdAt: "7/3/2018",
updatedAt: "7/3/2018"
},
relationships: {
role: {
data: {
id: 3,
type: "roles"
}
}
},
type: "user_roles"
},
{
id: 2,
attributes: {
createdAt: "7/1/2018",
updatedAt: "7/1/2018"
},
relationships: {
role: {
data: {
id: 4,
type: "roles"
}
}
},
type: "user_roles"
}
]
const roles = [
{
id: 3,
attributes: {
name: "manager",
description: "manages stuff"
},
relationships: {
user_roles: {
data: [
{
id: 1,
type: "user_roles"
},
{
id: 10,
type: "user_roles"
}
]
}
},
type: "roles"
},
{
id: 4,
attributes: {
name: "director",
description: "directs stuff"
},
relationships: {
user_roles: {
data: [
{
id: 2,
type: "user_roles"
}
]
}
},
type: "roles"
},
]
我需要的是一个如下所示的用户对象:
const newUser = [
{
id: 1,
attributes: {
firstName: "Bob",
lastName: "Lee"
},
relationships: {
user_roles: {
data: {
id: 1,
type: "user_roles"
}
}
},
type: "users",
included: [
{
role: {
name: "manager",
description: "manages stuff"
}
}
]
},
{
id: 2,
attributes: {
firstName: "Kevin",
lastName: "Smith"
},
relationships: {
user_role: {
data: {
id: 2,
type: "user_roles"
}
}
},
type: "users",
included: [
{
role: {
name: "director",
description: "directs stuff"
}
}
]
},
];
我学会了如何将两个数组合并在一起,但是拥有这个“中间”数组真的让我很反感,我什至不知道从哪里开始!
【问题讨论】:
标签: javascript arrays object ramda.js