Standardize keys in array of objects

I am dealing with a JSON response from a webservice that drops keys if the value is null. This practice is reasonable enough, but I am using the the response as a data source for a reporting component that uses the first value in the array of objects as the source of truth for all fields available within the rest of the objects.

The reporting component is calling a serverless javascript endpoint that I write and control. So I can process the results and potentially standardize the JSON object keys in this js code prior to send the response.

Making things trickier, the shape and/or fields of the data is variable. It is the result of a user supplied GraphQL query.

So a query like this:

    query GetCustomersByState($state: String!) {
      Customer(where: { State: { _eq: $state } }) {

Might result in:

      CustomerID: 'TENASPH',
      CustomerName: 'Tennessee Asphalt',
      Address1: '123 main st',
      City: 'Somewhere',
      State: 'TN'
      CustomerID: '10002',
      CustomerName: 'A&N Drywall',
      Address1: '123 Drywall Ln',
      Address2: 'Suite 2',
      City: 'Somewhere',
      State: 'TN',
      Zip: '12345'
      CustomerID: 'JONES',
      CustomerName: 'Jones Bros Construction',
      City: 'Somewhere',
      State: 'TN',
      Zip: '37917'

How can I standardize the keys across the array of objects?

(If helpful, the data source is a Hasura GraphQL server instance. I have looked around the Hasura interface and can't seem to find any settings that would include blanks in the response. Would be great if that did exist.)

Read more here:

Content Attribution

This content was originally published by Eric Wilhite at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: