-2

I have some line of code that I don't fully understand. I am looking through objects in an api and was wondering what is the purpose of the [i] in d2.follows[i].user.display_name if the code is:

$.getJSON(followerURL, function(d2){
  for(var i=0; i<d2.follows.length; i++){
    var displayName = d2.follows[i].user.display_name;
 following.push(displayName);

I'm searching through object to find the number of followers a channel has. is Here is an image of the object I would greatly appreciate an explanation of this block of code.

Baquino
  • 51
  • 6
  • 1
    `folows` is an array and `folows[i]` is an element of this array. what is the question? – diavolic Aug 24 '17 at 05:46
  • d2.foolows is an Array of objects – Ivan Minakov Aug 24 '17 at 05:46
  • It accesses element number `i` from the array `d2.follows`. – Nisarg Shah Aug 24 '17 at 05:46
  • As per your Json Data if you want all display_name then your code should be `dd2.follows.user[i].display_name;` – Blue Aug 24 '17 at 05:46
  • 1
    It would be good to read what a [for loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) is – aug Aug 24 '17 at 05:46
  • you want to get all indices of `follows` from `0` to `follows.length` (may be it is has 10 or 100 elements..) in each iteration `i` will be increment by `i++`. In the first iteration `i` is `0` and in the last it is `follows.length - 1`. Now you get all elements because you can simply write `d2.follows[i]` to get the element at the `i` position. – Roman Aug 24 '17 at 05:49

4 Answers4

0

As per you JSON Object, it fetches the follows element, which is an array. Then it takes each element in the follows array and get the user object and its attribute display_name.

Obj -> follows -> user -> display_name

This lists down all the display names of the users.

Maddy
  • 2,114
  • 7
  • 30
  • 50
0

d2.follows should b an array of objects

To get the displayName from each objects, we should iterate through the array. The [i] helps to iterate through the array elements.

joss
  • 695
  • 1
  • 5
  • 16
0

The [i] in d2.follows[i].user.display_name uses the i value from the for loop to set displayName. More or less it goes through the array one by one and reads a value.

I'm unfamiliar with the Twitch API, but if the follows array consists of people who are following someone, then follows.length will give you the amount of followers.

sham
  • 1,214
  • 10
  • 16
0

getJSON function return you this object here d2 main object returned from function. for(var i=0; i<d2.follows.length; i++) loop for get each item in the follows list. var displayName = d2.follows[i].user.display_name; here d2.follows[i] is a each item and each item have a user property which is a object and have a display_name property here you set last one property to displayName variable then you call following.push(displayName); following suspect is a array which is a have a push method