JSFiddle - React, Tailwind, and code Playground

by Daniel Lizik

HTML

<pre id="pre"></pre>

JavaScript

var ref = {
  z: {},
  e: [],
  a: 'dog',
  b: 'cat',
  c: {
    a: 'elephant',
    b: {
      a: 'monkey',
      b: ['cat', 'dog', {
        a: 'lizard',
        b: 'squirrel'
      }]
    }
  },
  d: [
    4,
    56,
    null, [
      1,
      34, {
        a: 'cat'
      }
    ]
  ]
};

var lib = (function(global, factory) {
  'use strict';
  return factory();
})(this, function() {
  'use strict';

  function lib(ref) {
    var bucket = treewalk(ref, {}, '', '.');
    return bucket;
  }

  function treewalk(obj, bucket, pathStr, delim) {

    var i, p, last = pathStr.slice(0, pathStr.length - 1);

    if (Array.isArray(obj)) {
      if (obj.length === 0)
        bucket[last] = obj;
      else {
        for (i = 0; i < obj.length; i++)
          treewalk(obj[i], bucket, pathStr + i + delim, delim)
      }
    } else if (Object.prototype.toString.call(obj) === '[object Object]') {
      if (Object.keys(obj).length === 0)
        bucket[last] = obj;
      else {
        for (p in obj)
          treewalk(obj[p], bucket, pathStr + p + delim, delim);
      }
    } else if (typeof obj === 'number' || typeof obj === 'string' || obj === null)
      bucket[last] = obj;

    else if (obj === undefined)
      throw new Error('cannot pass undefined');

    return bucket;
  }

  return lib;

});

document.querySelector('#pre').textContent = JSON.stringify(lib(ref), null, 2)