javascripttypescriptalgorithm

JavaScript - Flatten nested JSON object


How could I turn this

{
  "root": {
    "sub": 1,
    "sub2": 2,
  },
  "root2": 3
}

into this

{
  "root.sub": 1,
  "root.sub2": 2,
  "root2": 3
}

though a function programmatically?

I have literally no idea how I would do it, but I've tried to create a function which uses a cursor/pointer to jump through all child objects, but could not find a way to repeat the process.


Solution

  • This may be an alternative;

    function flattenObject(obj, prefix = '') {
        let flattenedObject = {};
        
        for (let key in obj) {
            if (typeof obj[key] === 'object' && obj[key] !== null) {
                const nestedFlattenedObject = flattenObject(obj[key], prefix + key + '.');
                flattenedObject = {...flattenedObject, ...nestedFlattenedObject};
            } else {
                flattenedObject[prefix + key] = obj[key];
            }
        }
        
        return flattenedObject;
    }
    
    const nestedObject = {
      "root": {
        "sub": 1,
        "sub2": 2,
      },
      "root2": 3
    }
    
    const flattenedObject = flattenObject(nestedObject);
    console.log(flattenedObject);