TS-Scribe - v0.6.2
    Preparing search index...

    Function flattenObject

    • Flattens a nested object or array into a single-level object with dot-separated keys. This function recursively flattens the object, including arrays, to produce a key-value map where the keys represent the path to the original value, separated by dots.

      Type Parameters

      • T

        The type of the values in the flattened object.

      Parameters

      • object: Record<string, unknown>

        The object or array to flatten.

      • prefix: string = ''

        The prefix to use for nested keys (used recursively).

      Returns Record<string, T>

      A new object with flattened keys and values.

      const obj = {
      a: 1,
      b: { x: 2, y: [3, 4] },
      c: { z: { w: 5 } }
      };
      const flattened = flattenObject(obj);
      console.log(flattened);
      // Output: {
      // 'a': 1,
      // 'b.x': 2,
      // 'b.y.0': 3,
      // 'b.y.1': 4,
      // 'c.z.w': 5
      // }

      const arr = [1, [2, 3], { a: 4 }];
      const flattenedArr = flattenObject(arr);
      console.log(flattenedArr);
      // Output: {
      // '0': 1,
      // '1.0': 2,
      // '1.1': 3,
      // '2.a': 4
      // }