Search code examples
javascriptnormalizr

Rename result property in normalizr


Given data like:

{
  id: 1,
  ownerName: 'bob',
  devices: [
    {
      id: 2
    },
    {
      id: 3
    }
  ]
}

how would I convert it to the following object

{
  result: 1,
  entities: {
    owners: {
      1: {
        id: 1,
        ownerName: 'bob',
        deviceIds: [2, 3]
      }
    },
    devices: {
      2: {
        id: 2
      },
      3: {
        id: 3
      }
    }
  }
}

using normalizr? I can't figure out how to change devices to deviceIds in the returned result...


Solution

  • You can use the Process Strategy for this. It allows you to manipulate your data before it is processed. Simply return a copy of your object with the keys changed from the processStrategy() method.

    const Device = schema.Entity('devices');
    
    const Owner = schema.Entity(
        'owners',
        {
            deviceIds: [ Device ]
        },
        {
            processStrategy: value => ({
                id: value.id,
                ownerName: value.ownerName,
                deviceIds: value.devices
            })
        }
    );