Skip to content

Instantly share code, notes, and snippets.

@savayer
Created February 15, 2024 13:48
Show Gist options
  • Save savayer/3a40e0acd32cd750b83ed7c036c7cad6 to your computer and use it in GitHub Desktop.
Save savayer/3a40e0acd32cd750b83ed7c036c7cad6 to your computer and use it in GitHub Desktop.
/**
* It converts object {"id": "1,2", "type": "someType", "value": "abc"}
* to filter[id]=1%2C2&filter[type]=someType&filter[value]=abc
* */
export default function toJsonApiFilter(
obj: Record<string, any> | undefined,
): string {
const queryStringParts: string[] = [];
if (!obj) {
return '';
}
for (const key in obj) {
const encodedKey = `filter[${key}]`;
const encodedValue = encodeURIComponent(obj[key]);
queryStringParts.push(`${encodedKey}=${encodedValue}`);
}
return queryStringParts.join('&');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment