How to map values returned by indexes

I have the next index, which contains the value of the element name.

Here is an example of the query result:

q.Paginate(q.Match(q.Index("all_topic_details")), { size: 10000 }

{
  data: [
    ["Test value 1", Ref(Collection("topics"), "298887387827829106")],
    ["Test value 2", Ref(Collection("topics"), "298882978413090259")],
    ["Test value 3", Ref(Collection("topics"), "298881581691676332")]
  ]
}

But I need the next output format:

[
  {
    id: "298887387827829106",
    name: "Test value 1"
  },
  {
    id: "298882978413090259",
    name: "Test value 2"
  },
  {
    id: "298881581691676332",
    name: "Test value 3"
  }
]

Can you tell how to transform to the desired format?

1 Like

You can use a combination of Map, Lambda, and Let. Something like this:

Map(
  Paginate(Match(Index("all_topic_details"))),
  Lambda(
    "result",
    Let(
      {
        id: Select([1, 'id'], Var('result')),
        name: Select([0], Var('result')),
      }
    )
  )
)

You use Select with a path like [1, 'id'] to select values on objects and arrays. In this case, you’re getting an array from the index result, and then selecting the id from the ref.

You can learn about using indexes on this tutorial:

I get the next error:

Error: Let function requires 2 argument(s) but 1 were given
For more info, see the docs: https://docs.fauna.com/fauna/current/api/fql/functions/let

I have also tried this, but then I get the next error:

Map(
  Paginate(Match(Index("all_topic_details"))),
  Lambda(
    "result",
    Let(
      {
        topicRef: Var("result"),
      },
      {
        id: Select([1, 'id'], Var(topicRef)),
        name: Select([0], Var(topicRef)),
      }
    )
  )
)

Error: topicRef is not defined

Oops sorry @Tuan I didn’t test that :slight_smile:

In fact you can actually skip using Let. See this example:

Map(
  [["hello","world"], ["hello","world"]],
  Lambda(
    "result",
      {
        id: Select([0], Var('result')),
        name: Select([1], Var('result')),
      }
  )
)

// Returns

[
  {
    id: "hello",
    name: "world"
  },
  {
    id: "hello",
    name: "world"
  }
]

You were almost there, except that you have to pass the name of the variable as a string. Instead of doing Var(topicRef) it should have been be Var("topicRef").

Another point is that, in your latest example, Var("result") that you named topicRef is not actually a ref, but simply an array with index values. You can of course name your vars in any way you wish.

It works like a charm now. Thanks @pier