Skip to content

Instantly share code, notes, and snippets.

@Helveg
Created February 24, 2022 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Helveg/2663c8ef09bc0c27c68419c6d06215ea to your computer and use it in GitHub Desktop.
Save Helveg/2663c8ef09bc0c27c68419c6d06215ea to your computer and use it in GitHub Desktop.
Deep and nested query parameters for Angular, for use with things like Strapi
class DeepQuery {
constructor(public query: any) {
}
private isObj(obj: any): boolean {
return (
typeof obj === 'object' &&
obj !== null
)
}
private toQPK(crumbs: string[]): string {
if (crumbs.length == 0) {
throw new Error(`Parameter without key`)
}
return crumbs[0] + crumbs.slice(1).map(s => `[${s}]`).join("");
}
private parse(obj: any, crumbs: string[] = [], memo: {[key: string]: any} = {}) {
if (!this.isObj(obj)) {
memo[this.toQPK(crumbs)] = obj;
} else if (Array.isArray(obj)) {
for (let i = 0; i < obj.length; i++) {
crumbs.push(i.toString());
this.parse(obj[i], crumbs, memo);
crumbs.pop();
}
} else {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
crumbs.push(key);
this.parse(obj[key], crumbs, memo)
crumbs.pop();
}
}
}
return memo;
}
public encode() {
return this.parse(this.query);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment