I am trying to merge two objects fetched from response distance matrix api into one. Distance matrix api can't accept more than 25 set of lat and long data. Hence with the help of for loop i am trying to run the distance matrix api multiple times and merge the results, so that it can be used.
let distanceMatrixData = []; let countk = 0; for(let k = 0; k<destlatlongArr.length; k++ ){ Request.get( `${gmapBaseUrl}/distancematrix/json?origins=${custlatlong}&destinations=${destlatlongArr[k]}&key=${process.env.googleMapsKey}`, (error, response, body) => { if (error) { return res.status(500).json({ success: 0, error: error, message: "Error in distance matrix Api", }); } console.log("Response of Distance Matrix Api is below : "); distanceMatrixData = JSON.parse(body).rows[0]; //this always gives with 2nd iteration data . I also tried distanceMatrixData.push(JSON.parse(body).rows[0]); but it would create two different set of data countk++; if(countk == destlatlongArr.length){ console.log(distanceMatrixData); } }); } I have destlatlongArr.length as 2 and it can be even more in future. I wanted the data in JSON.parse(body).rows[0] to always be filled in distanceMatrixData Array.
1st set of data in JSON.parse(body).rows[0] is below :
{ elements: [ { distance: { text: "2 m", value: 2, }, duration: { text: "2 min", value: 2, }, status: "OK", }, { distance: { text: "3 m", value: 3, }, duration: { text: "3 min", value: 3, }, status: "OK", } ], } Second set of data in JSON.parse(body).rows[0] is below:
{ elements: [ { distance: { text: "4 m", value: 4, }, duration: { text: "4 min", value: 4, }, status: "OK", }, { distance: { text: "4 m", value: 4, }, duration: { text: "4 min", value: 4, }, status: "OK", } ], } I want two data merged in distanceMatrixData as below (also all the objects in elements from both iteration to be merged to elements of distanceMatrixData so that i get the merged data) :
{ elements: [ { distance: { text: "2 m", value: 2, }, duration: { text: "2 min", value: 2, }, status: "OK", }, { distance: { text: "3 m", value: 3, }, duration: { text: "3 min", value: 3, }, status: "OK", }, { distance: { text: "4 m", value: 4, }, duration: { text: "4 min", value: 4, }, status: "OK", }, { distance: { text: "4 m", value: 4, }, duration: { text: "4 min", value: 4, }, status: "OK", } ], }