A walkthrough of a recursive algorithm problem.

The Problem:

Given an object oldObj, write a function flattenObject that returns a flattened version of it. 

If a certain key is empty, it should be excluded from the output. 
When you concatenate keys, make sure to add the dot character between them. For instance when flattening KeyB, c and d the result key would be KeyB.c and KeyB.d. 
Example: 
const oldObject = {
    "KeyA": 1, 
    "KeyB":{
        "c": 2, 
        "d": 3, 
        "e":{
            "f": 7, 
            "" : 2
         }
      }
}
Output: 
{
    "KeyA": 1, 
    "KeyB.c": 2, 
    "KeyB.d": 3, 
    "KeyB.e.f": 7, 
    "KeyB.e": 2
}

Step 1: Understand the problem

The first step should always be to repeat the problem back and make sure you understand what it is doing. Are there any edge cases? In this case we are flattening out any nested objects into one single object and we will be assigning them to keys based on the object they were nested inside. We also know that if a key is empty that we still need to retain its value but the empty key is ignored when making our key names.

#coding-interviews #javascript #algorithms #coding #programming

How to Use Recursion to Flatten a JavaScript Object
9.15 GEEK