Home > Software design >  Make the code take one number at a time and embed in it
Make the code take one number at a time and embed in it

Time:04-18

I'm trying to use an API in my code that downloads media from Instagram posts.

The response passed by the API is as follows:

{
    post1: {
        url: 'download url',
        type: 'media type' 
    },
    post2: {
        url: 'download url',
        type: 'media type' 
    }
}

post1, post2, and so on depending on the number of posts on that link (up to 10 posts).

i would like it to query and get the url of each of them.

var resultsMedia = await apis.insta_post(link)

I tried

resultsMedia.post[i].url

(i refers to a for function I tried, for var i = 1; ...) and I was not successful.

I would like to know how I could make the resultsMidia.post take one number at a time example: resultsMedia.post1.url, resultsMedia.post2.url, resultsMedia.post3.url, and so on.

(resultsMedia refers to the API call, post refers to the api response, and url is a parameter also present in the API response)

CodePudding user response:

You can try:

const postCount=Object.keys(resultsMedia).length;
for (let i = 1;i<=postCount;i  ){
   console.log(resultsMedia[`post${i}`])
}

CodePudding user response:

You can iterate using Object.entries():

const response = {
  post1: {
    url: 'download url 1',
    type: 'media type'
  },
  post2: {
    url: 'download url 2',
    type: 'media type'
  }
}

Object.entries(response).forEach(([post, data]) => {
  console.log('---------------')
  console.log('Post:', post)
  console.log('Post number:',  post.replace('post', ''))
  console.log('Data:', data)
  console.log('Data url:', data.url)
  console.log('---------------')
})

  • Related