How to convert a nested JavaScript object to a flat array?
<p>I've been coding at this solution for hours now and can't seem to make much progress anymore. It's a very difficult function to write. Here is my input:</p>

<pre><code>var testObj = {
  'b': 'num',
  'a': {
    'd': 'num',
    'c': 'num'
  },
  'g': ['num', 'num', {
    'x': 'num',
    'y': 'num'
  }],
  'e': 'num'
};
</code></pre>

<p>And here's the output I'm trying to generate from above:</p>

<pre><code>var flatTestObj = [
  ['b', 'num'],
  ['a', 'obj'],
  ['a', 'obj', 'd', 'num'],
  ['a', 'obj', 'c', 'num'],
  ['g', 'arr'],
  ['g', 'arr', 0, 'num'],
  ['g', 'arr', 1, 'num'],
  ['g', 'arr', 2, 'obj'],
  ['g', 'arr', 2, 'obj', 'x', 'num'],
  ['g', 'arr', 2, 'obj', 'y', 'num'],
  ['e', 'num']
];
</code></pre>

<p>(Later I'm going to alphabetize the keys too but I can handle that part on my own so I excluded that from the question to make it easier to answer) but yeah the point is to guarantee the same order traversal of objects of this format later on.</p>

<p>Basically, have it recursively go through the object and add each key/index mapping as a new element to <code>flatTestObj</code> so later you can iterate through <code>flatTestObj</code> and get every member from <code>testObj</code> by referencing every other element from the current <code>flatTestObj</code> index array value.</p>

<p>Here's what I have so far but I'm having difficulty getting it to work with nesting:</p>

<pre><code>var flattened = [];

function flatten(json, acc) {
  var keys = Object.keys(json);

  for (var i = 0; i &lt; keys.length; i++) {
    var key = keys[i];
    var val = json[key];

    var strVal = typeof val === 'object' ? 'obj' : val;

    if (acc.length === 0) {
      acc = [key, strVal];
    } else {
      acc = acc.concat([key, strVal]);
    }

    if (typeof val === 'object') {
      flatten(val, acc);
    } else {
      flattened.push(acc);
      acc = [];
    }
  }
}

flatten(testObj, []);
</code></pre>