Daskus
Daskus

Reputation: 969

Normalizing not nested tree into nested with Normalizr

I have to normalize two responses from the server and store them in my store using normalizr. The first response gives me the sections, the second the posts. Sections have many posts. One post can only have one section.

First response (sections):

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

Second response (posts):

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

I want to normalize the responses into this schema:

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

Since the response is not nested I don't know how to define the Schemas.

Upvotes: 2

Views: 547

Answers (1)

steppefox
steppefox

Reputation: 1844

May be you can do that with simple code? Without any library? 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);
}

Upvotes: 2

Related Questions