flatten.ts 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Copyright (c) 2014, Hugh Kennedy
  2. // Based on code from https://github.com/hughsk/flat/blob/master/index.js
  3. //
  4. export default function flatten(target: object, opts?: { delimiter?: any; maxDepth?: any; safe?: any }): any {
  5. opts = opts || {};
  6. const delimiter = opts.delimiter || '.';
  7. let maxDepth = opts.maxDepth || 3;
  8. let currentDepth = 1;
  9. const output: any = {};
  10. function step(object: any, prev: string | null) {
  11. Object.keys(object).forEach((key) => {
  12. const value = object[key];
  13. const isarray = opts?.safe && Array.isArray(value);
  14. const type = Object.prototype.toString.call(value);
  15. const isobject = type === '[object Object]';
  16. const newKey = prev ? prev + delimiter + key : key;
  17. if (!opts?.maxDepth) {
  18. maxDepth = currentDepth + 1;
  19. }
  20. if (!isarray && isobject && Object.keys(value).length && currentDepth < maxDepth) {
  21. ++currentDepth;
  22. return step(value, newKey);
  23. }
  24. output[newKey] = value;
  25. });
  26. }
  27. step(target, null);
  28. return output;
  29. }