gpt4 book ai didi

javascript - JS normalizr 如何向实体添加不相关的键

转载 作者:行者123 更新时间:2023-11-30 15:18:12 24 4
gpt4 key购买 nike

我想用 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: []
}
}

最佳答案

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]
}
}

关于javascript - JS normalizr 如何向实体添加不相关的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44180692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com