title: Recursively fitting JavaScript object to a specific structure
body: <p>I have this problem where I cant really figure out how to implement this in code. I think that I will have to use to power of recursion to do this, but I am really struggling with it.</p>
  
  <p>I have this object (simplified for this question), where the nested depths can be unknown. </p>
  
  <pre><code> const allValues = {
    features: {
      title: 'features',
      description: 'some features',
      fields: {
        featureA: false,
        featureB: true,
        featureC: true
      }
    },
    otherthings: {
      title: 'otherthings',
      description: 'otherthingsdescription',
      fields: {
        nestedotherthings: {
          title: 'nestedotherthings',
          description: 'nestedotherthingsdescription',
          fields: {
            againnested: {
              title: 'againsnested',
              description: 'againsnested',
              fields: {
                finallynestedvalue: 1
              }
            },
            againnested2: {
              title: 'againsnested2',
              description: 'againsnested2',
              fields: {
                finallynestedvalue: 200
              }
            }
          }
        }
      }
    }
  }
  </code></pre>
  
  <p>I want to run this object through some code and get an output like this:</p>
  
  <pre><code>  const expected_output = {
    features: {
      featureA: false,
      featureB: true,
      featureC: true
    },
    othertings: {
      nestedotherthings: {
        againnested: {
          finallynestedvalue: 1
        },
        againnested2: {
          finallynestedvalue: 2
        }
      }
    }
  }
  </code></pre>
  
  <p>What I have tried: </p>
  
  <pre><code> const output = _(allValues).mapValues((value, key) =&gt; flattenFields({}, value, key)).value()
  
  function flattenFields(parent, current, key) {
    if (!current || !current.fields) {
      return current
    }
  
    return {
      ...parent,
      [key]: _(current.fields).mapValues((value, key) =&gt; flattenFields(current, value, key)).value()
    }
  }
  </code></pre>
  
  <p>I hope someone can help me with this and explain what I am doing wrong.</p>