I want to normalize my data with normalizr
. The problem is that I have in my data one key (teams
) that it does not have a relationship with the other data.
For example:
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',
}
]
}
And my schema:
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]);
How can I also add the teams to the entities object that generated by normalizr
? So the results need to be:
{
entities: {
products: {},
programs: {},
releases: {},
teams: []
}
}
normalizr
can handle disjoint sets of data if you tell it the encompassing schema of your data:
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]
});
will result in:
Notice that the result
object now consists of two arrays with the keys of your top-level entities.
{
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]
}
}