0

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)

felipe
  • 1
  • As the JSON response shows, you're working with an object with property names `post1`, `post2`, etc. so you're not working with an array and you can't just use an iteration counter to walk over each post. Instead, you need to iterate using the Object's keys. It's also a terrible API response, and if you _can_ get whoever's generating this to switch it to a true array in the future, you absolutely want to try to convince them to. You typically want a response like `{ total: 1234, posts: [ {...}, {...}, ... ]}` where you know how many posts there are in total, and which set out of that you got. – Mike 'Pomax' Kamermans Apr 17 '22 at 16:49

2 Answers2

0

You can try this:

const postCount=Object.keys(resultsMedia).length;
for (let i = 1;i<=postCount;i++){
   console.log(resultsMedia[`post${i}`])
}
Tanay
  • 871
  • 1
  • 6
  • 12
  • Thus, the API responds in json as I put it up there, several parameters, like post1, post2 and so on. What I wanted is some way for him to identify the amount of posts, and get the url parameter. Type:ResultsMedia.post1,ResultsMedia.post2, in a way that he would do it himself, you know? – felipe Apr 17 '22 at 16:30
  • in a way where the i (or the key you put) were numbers from 1 to 10, one at a time – felipe Apr 17 '22 at 16:32
  • [You shouldn't use `for..in` with an array.](https://stackoverflow.com/q/500504/8376184) Consider a `for..of` or a plain `for` instead. – FZs Apr 17 '22 at 16:32
  • @felipe I have changed my answer – Tanay Apr 17 '22 at 16:55
0

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('---------------')
})
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46