Skip to content

Add a "dedata" function to hoist data objects in deserialized objects to the top-level #1102

@Thao-Tran

Description

@Thao-Tran

This library is almost exactly what my team needs for handling JSON:API data, but one downside is that the deserialized relationships are nested under an extra "data" attribute. I understand from this comment that this is the desired default behaviour, but my team doesn't really need to handle the use case around linked relationships, so it'd be nice if there was a built-in way to flatten these objects a bit.

I was wondering if a new function could be introduced called "dedata" that performs similarly to the "deattribute" function but just hoists the data objects up.

The following is an example of how I'm thinking the function would work:

const response = {
  data: {
    type: 'people',
    id: '1',
    attributes: {
      name: 'Thao'
    },
    relationships: {
      coworkers: {
        data: [
          {
            type: 'people',
            id: '2'
          },
          {
            type: 'people',
            id: '3'
          }
        ]
      }
    }
  },
  included: [
    {
      type: 'people',
      id: '2',
      attributes: {
        name: 'Anthony'
      }
    },
    {
      type: 'people',
      id: '3',
      attributes: {
        name: 'Dave'
      }
    }
  ]
}

const deserializedData = deserialize(response)
// {
//   data: {
//     type: 'people',
//     id: '1',
//     name: 'Thao',
//     coworkers: {
//       data: [
//         {
//           type: 'people',
//           id: '2',
//           name: 'Anthony'
//         },
//         {
//           type: 'people',
//           id: '3',
//           name: 'Dave'
//         }
//       ]
//     }
//   }
// }

const data = dedata(deserializedData)
// {
//   type: 'people',
//   id: '1',
//   name: 'Thao',
//   coworkers: [
//     {
//       type: 'people',
//       id: '2',
//       name: 'Anthony'
//     },
//     {
//       type: 'people',
//       id: '3',
//       name: 'Dave'
//     }
//   ]
// }

I'd be happy to implement the changes for this as well!

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions