Home > database >  How to retrieve array value in Node.js and send to next calling API
How to retrieve array value in Node.js and send to next calling API

Time:12-06

I am new to I have a JSON response from an API , which I need to parse two values in the JSON and then pass those value to the next API. The challenge I have is , I will have N number of Array JSON response similar to the sample I am Showing below ,this is one sample json but there will be n number of json concatenated of the same structure.

Now I want to retrieve the id and messages.messageId value within customers object and pass the same as input to next API call. How could I retrieve the matching id and message id and save it in a list to send to next API

   "id":"64146c29",
   "Customers":[
      {
         "id":"4a61aaf2-c6bc-41ae-9ecd-041825135bf5",
         "startTime":"2022-11-29T16:00:07.623Z",
         "endTime":"2022-11-29T16:00:07.630Z",
         "attributes":{
            "contactId":"30000236925961000-B1"
         },
         "provider":"Beta",
         "peer":"7126e24c-affa-4fb8-a450-50a644764a32",
         "messages":[
            {
               "messageId":"ce67fba0ef44523f0d9a9d5dd5649642"
            }
         ],
         "type":"sms",
         "recipientCountry":"US",
         "recipientType":"mobile"
      },
      {
         "id":"bbed4f9c-1be7-4fe5-ba37-5e058e9f16c6",
         "startTime":"2022-11-29T16:00:07.626Z",
         "endTime":"2022-11-29T16:00:07.668Z",
         "attributes":{
            
         },
         "provider":"Beta",
         "peer":"fe49dd4a-012e-447b-b9fe-7667678756c7",
         "messages":[
            
         ],
         "type":"sms",
         "recipientCountry":"US",
         "recipientType":"tollfree"
      }
   ],
   "otherMediaUris":[
      
   ],
   "selfUri":"64146c29-fe0d-4482-935e-8b86be878cb9"
} ````

CodePudding user response:

To get this data (id and messageId) of each customer, you will have to loop over the customers array and return those value from each customer object.

const customersDataToSendToApi = customersDataFromApi.Customers.map(customer => {
return {customer.Id, customer.messages.messageId}
})

The customersDataToSendToApi is already an array which you can pass in the body of API POST request. I hope this helps.

Yes, you do the same thing to the array of multiple json since you say they have similar structure.

arrayOfMultipleJson.map(eachJson =>{
eachJson.Customers.map(customer => {
return {customer.Id, customer.messages.messageId}
})
})

Do you get the picture I am painting? If you don't mind me asking, what scenario makes you get multiple JSON in one API call?

  • Related