尝试规范化我的有效负载时出现一些问题,该有效负载包含与使用Normalizr的父类型相同类型的嵌套模式
例如,我有一个初始对象(Menu),它有一个子节(Sections),它是一个带有截面的对象数组,可以深入。
{
id: 123,
sections: [{
id: 1,
sections:[{ id: 4, sections: [ id: 5, sections: [] ] }]
}, {
id: 2,
sections:[]
}, {
id: 3,
sections:[]
}]
}
我开始创建一个menu
模式,该模式在定义中包含链接到sections
模式的部分,这些部分适用于第一次传递,但后来不会处理部分的子节点,所以我在section
模式中添加了一个具有相同名称的后续定义(值得一试),但它没有用。
const section = new schema.Entity('sections')
const sections = new schema.Entity('sections', {
sections: section
})
const menu = new schema.Entity('menu', {
sections: [ sections ]
})
section.define({ sections })
我希望最终得到以下对象:
{
entities: {
menu: {
sections: [1, 2, 3]
},
sections: [{
1: { id: 1, sections: [4] },
2: { id: 2, sections: [] },
3: { id: 3, sections: [] },
4: { id: 4, sections: [5] },
5: { id: 5, sections: [] },
}]
}
}
答案 0 :(得分:18)
您的sections
架构应为Array
。
const section = new schema.Entity('sections')
const sections = new schema.Array(section);
section.define({ sections });
const menu = new schema.Entity('menu', { sections });
然后,使用它......
const data = {
id: 123,
sections: [{
id: 1,
sections:[{ id: 4, sections: [ { id: 5, sections: [] } ] }]
}, {
id: 2,
sections:[]
}, {
id: 3,
sections:[]
}]
};
normalize(data, menu)
将返回:
{
"entities": {
"sections": {
"1": { "id": 1, "sections": [ 4 ] },
"2": { "id": 2, "sections": [] },
"3": { "id": 3, "sections": [] },
"4": { "id": 4, "sections": [ 5 ] },
"5": { "id": 5, "sections": [] }
},
"menu": {
"123": { "id": 123, "sections": [ 1, 2, 3 ] }
}
},
"result": 123
}
答案 1 :(得分:0)
如果某人具有相同“类型”(例如“ sections”)的嵌套对象,则顶层结构也是“ sections”的数组,例如:
const data = [
{
id: 1,
sections:[{ id: 4, sections: [ { id: 5, sections: [] } ] }]
},
{
id: 2,
sections:[]
},
{
id: 3,
sections:[]
}
]
这里是“嵌套”它们的一种方法:
import {schema, normalize} from "normalizr";
const child = new schema.Entity("sections");
const sections = new schema.Array(child);
child.define({sections});
const topLevel = new schema.Entity("sections", {
sections
});
const customSchema = [topLevel];
console.log(normalize(data, customSchema));
您将获得的是:
{
"entities":{
"sections":{
"1":{
"id":1,
"sections":[
4
]
},
"2":{
"id":2,
"sections":[
]
},
"3":{
"id":3,
"sections":[
]
},
"4":{
"id":4,
"sections":[
5
]
},
"5":{
"id":5,
"sections":[
]
}
}
},
"result":[
1,
2,
3
]
}