@narrative.io/jsonforms-provider-protocols
Version: 
Dynamic data provider capabilities for JSONForms with Vue 3 integration
42 lines (39 loc) • 1.32 kB
text/typescript
export function jp(obj: unknown, path: string): unknown[] {
  // naive: support "$.a.b[*].c" & "$.items[*]"
  if (path === "$") return [obj];
  if (path === "") return [obj]; // Empty string should behave like "$"
  if (!path || typeof path !== "string") return [];
  // Handle array at root with $[*]
  if (path.startsWith("$[*]")) {
    if (!Array.isArray(obj)) return [];
    const remainingPath = path.slice(4); // Remove "$[*]"
    if (!remainingPath) return obj;
    if (remainingPath.startsWith(".")) {
      // Continue with remaining path for each array element
      const subPath = remainingPath.slice(1);
      const results: unknown[] = [];
      for (const item of obj) {
        results.push(...jp(item, subPath));
      }
      return results;
    }
    return [];
  }
  const parts = path.replace(/^\$\./, "").split(".");
  let current: unknown[] = [obj];
  for (const part of parts) {
    const next: unknown[] = [];
    const m = part.match(/^(\w+)(\[\*\])?$/);
    if (!m) return [];
    const key = m[1];
    if (!key) return [];
    const star = !!m[2];
    for (const c of current) {
      const v = (c as Record<string, unknown>)?.[key];
      if (star && Array.isArray(v)) next.push(...v);
      else if (!star && v !== undefined) next.push(v);
    }
    current = next;
  }
  return current;
}