skip to Main Content

I am already spending hours, and I think it is a small problem. Actually I can not find any solutions yet that fit for me (like make a new method to handle arrays in javascript, because I have to use the prebuilt functions of the Facebook Api).

I want to collect all the data from a Facebook account, but some of this data are in Arrays located, such as Likes, Feed, Favorite_teams, etc.

How can I display all this array data in a single line (I only need the text itself, and so not the ID of a post, or creation date).

For example for likes I make the following code in Javascript:

for (i = 0; i < response.likes.data.length; i++){
                document.getElementById('likes').innerHTML = response.likes.data[i].name;
                }

But when I print the Div of course it shows the last element of the array. How can I show them all?

3

Answers


  1. You are using = hence it will override the innerHTML every time.

    You should use += which is the equivalent of

    document.getElementById('likes').innerHTML = document.getElementById('likes').innerHTML + response.likes.data[i].name;
    

    In your code it will now be like this

    for (i = 0; i < response.likes.data.length; i++){      
        document.getElementById('likes').innerHTML += response.likes.data[i].name;
    }
    
    Login or Signup to reply.
  2. Every time in loop you are replacing the innerhtml value and so only the last element will be displayed in the end. So, Try this,

    for (i = 0; i < response.likes.data.length; i++){
        var arrVal = document.getElementById('likes').innerHTML;
        document.getElementById('likes').innerHTML = arrVal + response.likes.data[i].name;
    }
    
    Login or Signup to reply.
  3. var responseData = '';
    for (i = 0; i < response.likes.data.length; i++){
        responseData += response.likes.data[i].name;
    }
    document.getElementById('likes').innerHTML = responseData;
    

    Do not change innerHTML in a loop, and make sure to “add”, not “overwrite”.

    …or even better if there are many items:

    var responseData = '',
        likeData = response.likes.data;
    for (i = 0, count = likeData.length; i < count; i++){
        responseData += likeData[i].name;
    }
    document.getElementById('likes').innerHTML = responseData;
    

    Although, there will be no space between the names, so this would actually be better and just one line of code:

    document.getElementById('likes').innerHTML = response.likes.data.map(e => e.name).join(', ');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search