因此,我从服务器获得了一个类似于:
的JSON响应{
data: [
{ id: 1, type: 'person', emails: [ { id: 1 }, { id: 3 } ], phones: [] },
{ id: 2, type: 'person', emails: [ { id: 2 } ], phones: [ { id: 2 } ] },
{ id: 3, type: 'person', emails: [ { id: 4 } ], phones: [ { id: 3 }, { id: 3 }] }
],
included: [
{ id: 1, type: 'emails', ... },
{ id: 2, type: 'emails', ... },
{ id: 3, type: 'emails', ... },
{ id: 4, type: 'emails', ... },
{ id: 1, type: 'phones', ... },
{ id: 2, type: 'phones', ... },
{ id: 3, type: 'phones', ... }
]
}
data
属性是一组具有相同结构的联系对象。每个联系对象都有一系列相关的电子邮件和电话。
included
属性是所有类型的相关对象的数组,这意味着它们可以共享和id或甚至具有不同的对象结构。
我希望尝试将响应变得更容易使用并且类似于:
{
entities: {
contacts: [ ... ],
emails: [ ... ],
phones: [ ... ]
},
result: [ 1, 2, 3 ]
}
我已设法使用以下方法规范化联系人数据:
const contactSchema = new schema.Entity('contacts');
const contactListSchema = [ contactSchema ];
const normalizedData= normalize(response, contactListSchema);
但显然不会在entities
中包含电子邮件或手机。
我实际上并不知道这个图书馆能否达到我想要实现的目标,但我们将不胜感激。
虽然不是基于上面的数据,但API基于jsonapi.org架构,因此主页上的示例与结构完全匹配。
答案 0 :(得分:1)
我实际上找到了一个专门设计用于基于原始normalizr执行此操作的库:
https://github.com/stevenpetryk/jsonapi-normalizer
希望这有助于将来的某个人!