Search code examples
javascriptvuexnormalizr

How to get id from main Entity and wrap it into nested one in normalizr


Hi I have a problem with normalization of my wrapped object.

I have a data array of dashboards and layouts object which contains breakpoints for responsive views.

Want to normalize them all into Two Entities, I mean Dashboards and Layouts.

{
   "dashboards":[
      {
         "id":1,
         "name":"First",
         "mode":"2",
         "layouts":{
            "lg":[
               {
                  "x":0,
                  "y":0,
                  "w":2,
                  "h":2,
                  "i":"sm1"
               },
               {
                  "x":2,
                  "y":0,
                  "w":2,
                  "h":2,
                  "i":"sm2"
               }
            ],
            "md":[
               {
                  "x":2,
                  "y":0,
                  "w":2,
                  "h":2,
                  "i":"sm2"
               }
            ]
         }
      }
   ]
}

I tried to do it like that. But I cant get the key from Dashboards and put it to the Layouts, beacuse it's one to one relationship.

const layouts = new schema.Entity('layouts');
const mode = new schema.Entity('modes');


const dashboards = new schema.Entity('dashboards', {
    layouts: layouts,
    mode: mode
});
const dashboardListSchema = new schema.Array(dashboards);

const normalizedData = normalize(response, dashboardListSchema);

My output is like dat for now:

Dashboards: { "1": { "id": 1, "name": "Główny", "mode": "2" } }

Layouts: { "undefined": { "lg": [ { "x": 0, "y": 0, "w": 2, "h": 2, "i": "sm1" }, { "x": 2, "y": 0, "w": 2, "h": 2, "i": "sm2" } ], "md": [ { "x": 2, "y": 0, "w": 2, "h": 2, "i": "sm2" } ] } }

I want id of dashboard instead of undefined. Could anyone help me?


Solution

  • This is my solution :)

    const layouts = new schema.Entity('layouts', {}, {
        idAttribute: (value, parent) => parent.id
    });