flatten.ts 957 B

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, 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 (!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. }