因此,我从服务器收到一个 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);
但这显然不包括实体
中的电子邮件或电话。
我实际上不知道这个库是否能够实现我想要实现的目标,但任何帮助将不胜感激。
虽然不是基于上述数据,但该 API 基于 jsonapi.org schema,因此主页上的示例与结构完全匹配。
最佳答案
我实际上找到了一个基于原始的normalizr专门设计用于执行此操作的库:
https://github.com/stevenpetryk/jsonapi-normalizer
希望这可以帮助将来的人!
关于javascript - 如何使用 Normalizr 来展平具有不同类型对象的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41766127/