gpt4 book ai didi

javascript - 使用 Normalizr 将非嵌套树规范化为嵌套

转载 作者:行者123 更新时间:2023-11-29 21:21:56 24 4
gpt4 key购买 nike

我必须规范化来自服务器的两个响应,并使用 normalizr 将它们存储在我的商店中。第一个回复给了我章节,第二个回复给了我帖子。 版 block 有很多帖子一个帖子只能有一个部分

第一 react (部分):

[
{
id: 10,
title: "foo"
},
...
]

第二个回复(帖子):

[
{
id: 2,
sid: 10, //id of the section
title: "foo",
text: "foo foo"
},
...
]

我想将响应规范化到这个模式中:

{
entities: {
sections: {
10: {title: "foo", posts: [2, 5, 12, 152]},
15: {title: "example", posts: [1, 8]},
...
},
posts: {
1: {id: 1, sid: 15, title: "abc", text: "something"},
2: {id: 2, sid: 10, title: "foo", text: "foo foo"},
...
}
}
}

由于响应不是嵌套的,我不知道如何定义架构。

最佳答案

也许您可以用简单的代码做到这一点?没有任何图书馆?哦

var posts = [ ... ]; // some posts here
var sections = [ ... ]; // some sections here
var schema = { entities: { sections: {}, posts: {} } };

for (var i = 0; i < sections.length; i++) {
var section = sections[i];
schema.entities.sections[section.id] = {
title: section.title,
posts: []
}
}

for (var j = 0; j < posts.length; j++) {
var post = posts[j];
schema.entities.posts[post.id] = post;
schema.entities.sections[post.sid].posts.push(post.id);
}

关于javascript - 使用 Normalizr 将非嵌套树规范化为嵌套,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38350687/

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