flatMap()

Create an Set by applying a Function to each Set element, then flatten the result by one level.

Lazy loading:

Yes

Signature

flatMap(function: (element: Any) => Set): Set

Description

The flatMap() method creates an Set by invoking function on each element of the calling set and flattening the resulting set one level. The Set elements are passed as a parameter to function, sequentially.

the calling set isn’t changed.

Parameters

Parameter Type Required Description

function

Function

Yes

Function to invoke for each Set element that the Set represents. Each Set element is passed to function as an argument. function must return an Set

function parameters:

Parameter Type Required Description

element

Any

Yes

Set element to evaluate.

Return value

Type Description

Set

Set of the result of calling function on each element of the calling set. The resulting set is flattened by one level.

Examples

flatmap() is similar to map(), except it flattens the resulting Set.

The following query uses map() and returns a nested set. It uses Fauna’s demo data.

// Returns a set
let topCustomer = Customer.byName("Alice", "Appleseed")

// Returns a nested set
topCustomer.map((customer) => Order.byCustomer(customer))
{
  data: [
    {
      data: [
        {
          id: "392698761120317504",
          coll: Order,
          ts: Time("2024-03-18T12:39:32.610Z"),
          customer: Customer.byId("392698761099345984"),
          ...
        }
      ]
    }
  ]
}

The following query uses flatmap() to flatten the returned set.

// Returns a set
let topCustomer = Customer.byName("Alice", "Appleseed")

// Returns a flattened set 
topCustomer.flatMap((customer) => Order.byCustomer(customer))
{
  data: [
    {
      id: "392698761120317504",
      coll: Order,
      ts: Time("2024-03-18T12:39:32.610Z"),
      customer: Customer.byId("392698761099345984"),
      ...
    }
  ]
}

Is this article helpful? 

Tell Fauna how the article can be improved:
Visit Fauna's forums or email docs@fauna.com

Thank you for your feedback!