Using the input given, I need to join the true "user" value from the tweets array with the id in the users array and display the users array object as part of the tweets array
Input:
{
"tweets": [
{
"tweet": "Hey, i gonna release GPT4 soon",
"user": 1
},
{
"tweet": "We have launched falcon 10 yesterday, it was awesome, one step closer to Mars",
"user": 2
},
{
"tweet": "Databar acquires Statista.com, great news coming out",
"user": 3
},
{
"tweet": "Gpt4 is available",
"user": 1
}
],
"users": [
{ "id": 1, "name": "a" },
{ "id": 2, "name": "b" },
{ "id": 3, "name": "c" }
]
}
Output
[
{
"tweet": "Hey, i gonna release GPT4 soon",
"user": {
"id": 1,
"name": "a"
}
},
{
"tweet": "We have launched falcon 10 yesterday, it was awesome, one step closer to Mars",
"user": {
"id": 2,
"name": "b"
}
},
{
"tweet": "Databar acquires Statista.com, great news coming out",
"user": {
"id": 3,
"name": "c"
}
},
{
"tweet": "Gpt4 is available",
"user": {
"id": 1,
"name": "a"
}
}
]
I tried using an if condition to find the equal values first, but it loops through the entire array, hence I cant get the specific value of the value in the users array that the ID is equal too
2
Answers
Build an
INDEX
, then use that to map your tweets:or using
JOIN
directly:You could also do it the inefficient way, finding the correct user by iterating:
@knittl’s solutions using INDEX are fine unless there is a "collision" of ids (e.g. if .id can be both
1
and"1"
).To avoid collisions and to allow other types of
.id
values, you could useSAFE_INDEX
andlookup
defined as follows:So a generic solution to the problem would look like this: