Search code examples
normalizr

Normalizing a nested entity that shares the current schema


My goal is to normalize this object:

{
  talks: [
    {
      id: 1755,
      speakers: [
        {
          id: 1487,
          name: 'John Doe',
        },
      ],
      related_talks: [{
        id: 14,
        speakers: [{
          id: 125,
          name: 'Jane Doe',
        }],
        event: {
          id: 181,
          name: 'First Annual',
        },
      }],
      event: {
        id: 180,
        name: 'July Party',
      },
    },
  ],
};

into this result:

{
  entities: {
    events: {
      181: {
        id: 181,
        name: 'First Annual'
      },
      180: {
        id: 180,
        name: 'July Party'
      }
    },
    speakers: {
      125: {
        id: 125,
        name: 'Jane Doe'
      },
      1487: {
        id: 1487,
        name: 'John Doe'
      }
    },
    talks: {
      1755: {
        id: 1755,
        event: 181,
        speakers: [ 1487 ],
        related_talks: [ 14 ],
      },
      14: {
        id: 14,
        speakers: [ 125 ],
        event: 180,
      }
    },
  },
  result: {
    talks: [ 1755, 14 ],
  },
}

If you'll notice, the items in related_talks are treated the same as a talk.

My schemas follow the examples and are set up like this:

const speaker = new schema.Entity('speakers');
const event = new schema.Entity('events');

export const talk = new schema.Entity('talks', {
  speakers: [speaker],
  event,
});

talk.define({ related_talks: [talk] });

No matter what I try, I can't get the items in related_talks to be added to the result.talks array. It is, however, in the entities object.

What is my schema configuration missing in order to accommodate this?


Solution

  • Unfortunately, if this is your requirement, Normalizr is not for you. Alternatively, if you're looking for a list of "talks" by ID, you can use Object.keys(data.entities.talks)