Tom Nolan
Tom Nolan

Reputation: 1957

How to use normalizr to flatten an array with different types of objects?

So, I get a JSON response from the server that looks something like:

{
  data: [
     { id:  1, type: 'person', emails: [ { id: 1 }, { id: 3 } ], phones: []  },
     { id:  2, type: 'person', emails: [ { id: 2 } ], phones: [ { id: 2 } ]  },
     { id:  3, type: 'person', emails: [ { id: 4 } ], phones: [ { id: 3 }, { id: 3 }]  }
  ],
  included: [
     { id: 1, type: 'emails', ... },
     { id: 2, type: 'emails', ... },
     { id: 3, type: 'emails', ... },
     { id: 4, type: 'emails', ... },
     { id: 1, type: 'phones', ... },
     { id: 2, type: 'phones', ... },
     { id: 3, type: 'phones', ... }
  ]
}

The data property is an array of contact objeccts all with the same structure. Each contact object has an array of related emails and phones.

The included property is an array of ALL types of related objects which means they can share and id or even have a difference object structure.

I'm looking to try and flatten the response to be easier to work with and resemble:

{
    entities: {
        contacts: [ ... ],
        emails: [ ... ],
        phones: [ ... ]
    },
    result: [ 1, 2, 3 ] 
}

I've managed to normalize just the contact data using:

const contactSchema = new schema.Entity('contacts');
const contactListSchema = [ contactSchema ];
const normalizedData= normalize(response, contactListSchema);

But that obviously won't include the emails or phones in the entities.

I don't actually know if this library is capable of what I'm trying to achieve, but any help would be appreciated.

While not based on the data above, the API is based off of the jsonapi.org schema, so the example on the homepage matches exactly with the structure.

Upvotes: 1

Views: 839

Answers (1)

Tom Nolan
Tom Nolan

Reputation: 1957

I actually found a library specifically designed to do this based on the original normalizr:

https://github.com/stevenpetryk/jsonapi-normalizer

Hope this may help someone in the future!

Upvotes: 1

Related Questions