So this took some time to figure out. The real problem here is keeping track of the indexes between the arrays. Thats why I would rather opt to restructure how the data is stored because this is a lot of work just to make an object. However, I have taken the time to figure out how to solve this if that is not possible for you.
Let(
{
firstArr: ['302130074358907392', 'John', 42],
secondArr: ['id', 'name', 'age'],
arrWithInd: Reduce(
Lambda(
["acc", "val"],
Append([[Var("val"), Count(Var("acc"))]], Var("acc"))
),
[],
Var("firstArr")
),
combinedArrs: Map(
Var("arrWithInd"),
Lambda(
"tupleArr",
Append(
[Select(0, Var("tupleArr"))],
[Select(
Select(1, Var("tupleArr")),
Var("secondArr")
)
]
)
)
),
arrToObj: ToObject(Var("combinedArrs"))
},
Var("arrToObj")
)
result:
{
id: '302130074358907392',
name: 'John',
age: 42
}
Okay so what is going on here? In order to keep track of the indexes, I made an array of arrays that stores the index as the second value in the arrWithInd variable using a helper FQL library I found on Github called WithIndex
. The source code is in the src/functions
folder. GitHub - shiftx/faunadb-fql-lib
In this case, it would translate to
[['302130074358907392', 0], ['John', 1], [42, 2]]
Once you have the indexes, the rest is relatively straight forward. Combining the arrays just becomes a matter of mapping over the array with your index and then using that index to dynamically select the value from the other array. Since the values in the array of tuples are known, I am using Select(0, …) and Select(1, …) where Select(0, …) is the value and Select(1,…) is the index of that value.
Then to get the final array of arrays back, I used Append to I just store the values into two array literals to get back the structure that you want. And the last step is using ToObject() as you requested to turn that array of arrays back into an object.
Now I will note that there is still a fundamental assumption baked into this which is that both of the arrays are the same length. I would presume they would have to be if you are trying to make key value pairs of each corresponding element in both arrays. I would put a guard to check if this were true. It might look something like this
If(
Equals(Length(Var("firstArr")), Length(Var("secondArr")),
Let(...),
Abort("Array lengths are not equal.")
)
There may be an easier way to do this, but I haven’t seen a way to loop through both arrays at the same time and keep track of the individual elements from each array simultaneously (in which case you would just append them to an array without the step of knowing their index).