Guest User

Untitled

a guest
Nov 24th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. function flatten(source, key) {
  2. let it, index = 0;
  3. const flattened = {};
  4. const delim = key !== undefined ? '.' : '';
  5. key = key || '';
  6.  
  7. if (typeof source === 'string') {
  8. flattened[key] = source;
  9. return flattened;
  10. }
  11.  
  12. for (const prop in source) {
  13. it = source[prop];
  14. // STEP 2 - determine if the value property is an object, array, or value
  15. if (Array.isArray(it)) {
  16. // STEP 2.1 - it's an array, iterate over the array and get key for each obj
  17. index = 0;
  18. for (const obj of it) {
  19. key = delim + prop + '.' + index;
  20. Object.assign(flattened, flatten(obj, key));
  21. index++;
  22. }
  23. } else if (typeof it === 'object' && it !== null) {
  24. // STEP 2.2 - it's an object, traverse
  25. Object.assign(flattened, flatten(it, key + delim + prop));
  26. } else {
  27. // STEP 2.3 - The leaf - set the value
  28. flattened[key + delim + prop] = it;
  29. }
  30. }
  31. return flattened;
  32. }
Add Comment
Please, Sign In to add comment