flatten.ts 997 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  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, opts): any {
  5. opts = opts || {};
  6. var delimiter = opts.delimiter || '.';
  7. var maxDepth = opts.maxDepth || 3;
  8. var currentDepth = 1;
  9. var output = {};
  10. function step(object, prev) {
  11. Object.keys(object).forEach(function(key) {
  12. var value = object[key];
  13. var isarray = opts.safe && Array.isArray(value);
  14. var type = Object.prototype.toString.call(value);
  15. var isobject = type === '[object Object]';
  16. var newKey = prev ? prev + delimiter + key : key;
  17. if (!opts.maxDepth) {
  18. maxDepth = currentDepth + 1;
  19. }
  20. if (
  21. !isarray &&
  22. isobject &&
  23. Object.keys(value).length &&
  24. currentDepth < maxDepth
  25. ) {
  26. ++currentDepth;
  27. return step(value, newKey);
  28. }
  29. output[newKey] = value;
  30. });
  31. }
  32. step(target, null);
  33. return output;
  34. }