flatten
Overview
Section titled “Overview”The flatten
function recursively traverses a nested structure, such as an object, array, set, or map, and returns a flattened version of the structure. This means that it removes any nested references and produces a structure containing no refs.
Flattening Nested Structures
Section titled “Flattening Nested Structures”To flatten a nested structure, simply pass the reference to the flatten
function. It will return a new structure with all nested references removed.
import { flatten, ref } from 'regor'
const nestedData = { name: 'John', age: ref(30), hobbies: ['reading', 'swimming', ref('drawing')],}
const flattenedData = flatten(nestedData)
console.log(flattenedData)// Outputs: { name: 'John', age: 30, hobbies: [ 'reading', 'swimming', 'drawing' ] }
Parameters
Section titled “Parameters”reference
: The nested structure (object, array, set, map) that you want to flatten. It can contain nested refs, which will be resolved during flattening.
Return Value
Section titled “Return Value”- The
flatten
function returns a new structure that is a flattened version of the inputreference
. Any nested refs within the structure are resolved, resulting in a single-level structure.
-
The
flatten
function recursively flattens nested structures, including arrays, sets, maps, and objects. -
If the input
reference
contains refs, they are automatically unrefed during flattening, and their values are included in the flattened structure. -
Circular references within the input
reference
are not supported, and attempting to flatten such structures may result in unexpected behavior.
Example
Section titled “Example”import { flatten, ref } from 'regor'
const nestedData = { name: 'John', age: ref(30), hobbies: ['reading', 'swimming', ref('drawing')],}
const flattenedData = flatten(nestedData)
console.log(flattenedData)// Outputs: { name: 'John', age: 30, hobbies: [ 'reading', 'swimming', 'drawing' ] }