javascript - 使用 Normalizr 将非嵌套树标准化为嵌套树

标签 javascript reactjs redux normalizr

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

第一响应(部分):

[
  {
    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"},
      ...
    }
  }
}

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

最佳答案

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

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/

相关文章:

javascript - React DevTools 将组件显示为 "Loading..."

javascript - TS : export default functional component

javascript - 三.JS : object appears after zoom

javascript - html/css/javascript 中的动画线

javascript - 如何在 HTML5 中只接受字符值

javascript - 输入字段上的 e.target.value ReactJs,它是如何工作的?

javascript - redux 是否会在对 store 的任何更新时评估 store 的所有监听器?

reactjs - REACT 未捕获的 TypeError .then 不是一个函数

reactjs - React Redux - 等待数据加载

javascript - 如何判断画中画模式的留画类型?