How to flatten Object in JavaScript ?

Flattening an object is not a standard defined in JavaScript, however, it is commonly understood as the process of flattening out all nested values within an object into a flat single-level key-value structure, where each key represents a unique path to the original nested value.

function deepFlattenObject(input) {
  let result = Object.create({});

  for (const key in input) {
    if (Object.hasOwn(input, key)) {
      const value = input[key];

      if (typeof value !== 'object' || Object.is(null, value)) {
        result[key] = value;
      } else {
        result = {
          ...result,
          ...deepFlattenObject(value)
        };
      }
    }
  }

  return result;
}

const input = {
  a: 1,
  b: 2,
  c: 3,
  d: {
    e: 4,
    f: {
      g: null,
      h: 7
    }
  }
};
const output = deepFlattenObject(input);

/**
 * Yields:
 * {
    "a": 1,
    "b": 2,
    "c": 3,
    "e": 4,
    "g": null,
    "h": 7
  }
 */
console.log(output);
JavaScript

Stay tuned for more updates and detailed walkthroughs in the upcoming weeks. You can find more information about web development Happy coding! 🎉

Leave a Reply

Your email address will not be published. Required fields are marked *