Skip to content

Instantly share code, notes, and snippets.

@rjanjic
Created May 15, 2023 08:52
Show Gist options
  • Save rjanjic/13c45cce65191f21fe904c571d02add4 to your computer and use it in GitHub Desktop.
Save rjanjic/13c45cce65191f21fe904c571d02add4 to your computer and use it in GitHub Desktop.
Recursively remove __typename properties from a GraphQL response.
/**
* Recursively remove __typename properties from a GraphQL response.
*
* @param response The GraphQL response object.
* @return The cleaned response object.
*/
function stripTypename(response: any): any {
if (Array.isArray(response)) {
return response.map(stripTypename);
}
if (typeof response === 'object' && response !== null) {
return Object.fromEntries(
Object.entries(response)
.filter(([key]) => key !== '__typename')
.map(([key, value]) => [key, stripTypename(value)]),
);
}
return response;
}
const response = {
data: {
__typename: 'Query',
user: {
__typename: 'User',
id: '1',
name: 'John Doe',
posts: [
{
__typename: 'Post',
id: '1',
title: 'First post',
},
{
__typename: 'Post',
id: '2',
title: 'Second post',
},
],
},
},
};
console.log(stripTypename(response));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment