Write a function to flatten an object with nested objects.

Given an object with nested objects, this function flattens the object by creating key paths for nested values.

Problem

Given an object with nested objects, write a function that flattens the object.
Input:
{
  "a": 1,
  "b": {
    "c": 2,
    "d": {
      "e": 3
    }
  }
}
Output:
{
  "a": 1,
  "b.c": 2,
  "b.d.e": 3
}

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
function flattenObject(obj) {
  let result = {};
  for (let key in obj) {
    if (typeof obj[key] === "object") {
      let flatObject = flattenObject(obj[key]);
      for (let flatKey in flatObject) {
        result[key + "." + flatKey] = flatObject[flatKey];
      }
    } else {
      result[key] = obj[key];
    }
  }
  return result;
}

// This solution is optimal because it is recursive and will work for any number of nested objects.

A.I. Evaluation of the Solution

This solution is correct and demonstrates a level of completeness. It solves the problem and takes a general approach of flattening the object.

Evaluated at: 2022-11-27 08:16:31