我想用normalizr
规范化我的数据。问题是我在我的数据中有一个键(teams
),它与其他数据没有关系。
例如:
const data = {
programs: [{
id: 1,
label: 'Program one',
products: [{
id: 1,
label: 'Product one',
releases: [{
id: 1,
label: 'Release one',
}]
}
]
}
],
teams: [{
id: 1,
value: 1,
label: 'Team one',
}
]
}
我的架构:
const release = new schema.Entity('releases');
const product = new schema.Entity('products', {
releases: [release]
});
const program = new schema.Entity('programs', {
products: [product],
});
normalize(data, [program]);
如何将团队添加到normalizr
生成的实体对象?所以结果必须是:
{
entities: {
products: {},
programs: {},
releases: {},
teams: []
}
}
答案 0 :(得分:2)
normalizr
可以处理不相交的数据集:
const release = new schema.Entity('releases');
const product = new schema.Entity('products', {
releases: [release]
});
const program = new schema.Entity('programs', {
products: [product],
});
// add team entity
const team = new schema.Entity('teams');
// the encompassing schema
const dataschema = {
programs: [program],
teams: [team]
}
// normalize
normalize(data, dataschema);
// or omit dataschema definition and pass in directly
normalize(data, {
programs: [program],
teams: [team]
});
将导致:
请注意,result
对象现在包含两个数组,其中包含顶级实体的键。
{
entities: {
releases: {
1: {
id: 1,
label: "Release one"
}
},
products: {
1: {
id: 1,
label: "Product one",
releases: [1]
}
},
programs: {
1: {
id: 1,
label: "Program one",
products: [1]
}
},
teams: {
1: {
id: 1,
value: 1,
label: "Team one"
}
}
},
result: {
programs: [1],
teams: [1]
}
}