I’m trying to learn Normalization concept using object. I’m having doubt in that
Normal Array of Object:
const state = {
users: [
{ id: 1, name: "Alice", posts: [{ id: 101, title: 'Post 1', comments: [{ id: 202, text: 'comment 2' }, { id: 201, text: 'comment 1' }] }] },
{ id: 2, name: "Bob", posts: [{ id: 102, title: 'Post 2', comments: [{ id: 202, text: 'comment 2' }] }] }
],
tags: [
{ id: 301, name: 'Tech', posts: [{ id: 101, title: 'Post 1' }, { id: 102, title: 'Post 2' }] },
]}
Normalized structure
const state1 = {
users: {
byIds: {
1: { id: 1, name: "Alice", posts: [101] },
2: { id: 2, name: "Bob", posts: [102] }
},
allIds: [1, 2]
},
posts: {
byIds: {
101: { id: 101, title: 'Post 1', comments: [201] },
102: { id: 102, title: 'Post 2', comments: [202] }
},
allIds: [101, 102]
},
comments: {
byIds: {
201: { id: 201, text: 'comment 1' },
202: { id: 202, text: 'comment 2' }
},
allIds: [201, 202]
},
tags: {
byIds: {
301: { id: 301, name: 'Tech', posts: [101, 102] },
302: { id: 302, name: 'Travel', posts: [102] }
},
allIds: [301, 302]
}}
Now, inside normalized structure
state1.tags.byIds[‘302’] = { id : 302, name: ‘Travel’ , posts:[102] }
inside posts [102] value it has,
state1.posts.byIds[‘102’] = { id : 102 , title: ‘Post 2’, comments: [202] }
inside comments[202] value will be like this
state1.posts.comments[‘202’] = { id : 202, title: ‘comment 2’ }
so the normalised output of tags[302] value will be
{ id: 302, name: 'Travel', posts: { id: 102, title: 'Post 2', comments: { id: 202, text: 'comment 2' } } }
but in the non-normalized structure tags 302 value will be
{ id: 302, name: 'Travel', posts: [{ id: 101, title: 'Post 1' }] }
This both output is not same, how to normalize it correctly to get the same output ?
2
Answers
You can use normalizr package, it
This package is mentioned by Normalizing Nested Data documentation. For more info, see api docs.
The solution for your question:
Logs:
You could build by having a look to objects and arrays as properties.