All files / normalize normalize-deep-objects.ts

100% Statements 15/15
100% Branches 16/16
100% Functions 3/3
100% Lines 13/13

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28              160x 58x 130x 124x 165x   165x 165x 45x 139x 18x   121x     124x   6x      
import { snakeCase } from "../utils";
 
export function normalizeDeepObjects(
  obj: any,
  parentKey: string | number = "",
  res: any = {},
): any {
  if (Array.isArray(obj)) {
    return obj.map((item) => normalizeDeepObjects(item));
  } else if (typeof obj === "object" && obj !== null) {
    for (const key in obj) {
      const newKey = snakeCase(parentKey ? `${parentKey}.${key}` : key);
 
      const value = obj[key];
      if (Array.isArray(value)) {
        res[newKey] = value.map((item) => normalizeDeepObjects(item));
      } else if (typeof value === "object" && value !== null) {
        normalizeDeepObjects(value, newKey, res);
      } else {
        res[newKey] = value;
      }
    }
    return res;
  } else {
    return obj;
  }
}