Flattening Nested Objects

Given an object with nested objects, write a function to flatten the object (i.e. convert nested objects into a single level object).

Problem

Given an object containing nested objects, write a function that flattens the object (i.e. converts the nested objects into a single level object).
Example input:
const obj = {
  a: {
    b: 1,
    c: 2
  },
  d: {
    e: 3,
    f: 4
  }
};
Example output:
const flattenedObj = {
  a: {
    b: 1,
    c: 2
  },
  d: {
    e: 3,
    f: 4
  },
  b: 1,
  c: 2,
  e: 3,
  f: 4
};

Solution

This solution is in JavaScript. Our A.I. can create solutions in multiple languages.
by kayakane
const obj = {
  a: {
    b: 1,
    c: 2
  },
  d: {
    e: 3,
    f: 4
  }
};

const flatten = (obj) => {
  const flattenedObj = {};
  const flattenHelper = (obj) => {
    for (let key in obj) {
      if (typeof obj[key] === 'object') {
        flattenHelper(obj[key]);
      } else {
        flattenedObj[key] = obj[key];
      }
    }
  };
  flattenHelper(obj);
  return flattenedObj;
};

console.log(flatten(obj));

A.I. Evaluation of the Solution

The candidate's solution correctly flattens the object. The candidate uses a recursive approach to flatten the object, which is a good approach.

Evaluated at: 2022-11-25 10:17:01