I am making 2 api calls to receive two sets of data.
const callOne = await api('GET', `${baseUrl}callOne`);
const callTwo = await api('GET', `${baseUrl}callTwo`);
I can then output the results
console.log(callOne.data);
console.log(callTwo.data);
So resultOne is an array of objects. I am showing a couple of the objects below.
[
{
"id":1,
"name":"Some Name",
"description":"Some description",
"currency":"USD",
"price":"350",
"created_at":"2021-12-08T17:53:12.000Z",
},
{
"id":2,
"name":"Some Name",
"description":"Some description",
"currency":"USD",
"price":"12",
"created_at":"2021-12-08T17:53:12.000Z",
},
]
It is pretty much the same with resultTwo. Just showing a few results here.
[
{
"id":1,
"resultOneId":1,
"startDate":"2022-02-01T16:00:00.000Z",
"endDate":"2022-02-08T18:00:00.000Z",
"duration":"3 minutes",
"created_at":"2021-12-08T17:53:12.000Z",
},
{
"id":2,
"resultOneId":1,
"startDate":"2021-02-08T09:00:00.000Z",
"endDate":"2021-02-17T18:00:00.000Z",
"duration":"2 hours",
"created_at":"2021-12-08T17:53:12.000Z",
},
{
"id":3,
"resultOneId":2,
"startDate":"2021-02-08T09:00:00.000Z",
"endDate":"2021-02-17T18:00:00.000Z",
"duration":"5 hours",
"created_at":"2021-12-08T17:53:12.000Z",
},
]
What I am trying to do is create a new array of Objects, that essentially joins resultTwo with resultOne based on the resultOneId. So I would imaging ending up with something like this
[
{
"id":1,
"name":"Some Name",
"description":"Some description",
"currency":"USD",
"price":"350",
"created_at":"2021-12-08T17:53:12.000Z",
"resultTwos": [
{
"id":1,
"resultOneId":1,
"startDate":"2022-02-01T16:00:00.000Z",
"endDate":"2022-02-08T18:00:00.000Z",
"duration":"3 minutes",
"created_at":"2021-12-08T17:53:12.000Z",
},
{
"id":2,
"resultOneId":1,
"startDate":"2021-02-08T09:00:00.000Z",
"endDate":"2021-02-17T18:00:00.000Z",
"duration":"2 hours",
"created_at":"2021-12-08T17:53:12.000Z",
},
]
},
{
"id":2,
"name":"Some Name",
"description":"Some description",
"currency":"USD",
"price":"12",
"created_at":"2021-12-08T17:53:12.000Z",
"resultTwos": [
{
"id":3,
"resultOneId":2,
"startDate":"2021-02-08T09:00:00.000Z",
"endDate":"2021-02-17T18:00:00.000Z",
"duration":"5 hours",
"created_at":"2021-12-08T17:53:12.000Z",
},
]
},
]
I have been trying to attempt this using reduce and map but not got very far.
Any advice appreciated.
Thanks
>Solution :
Something as simple as:
resultOnes.map( one => {return { ...one, resultTwos: resultTwos.filter(two => two.resultOneId === one.id)}})