Emily Emily - 1 year ago 86
Javascript Question

How to store a Facebook Graph API response as a Javascript Array?

I'm wondering how to store the response from a Facebook API call into a Javascript array.

This is the call I'm making:

FB.api('/MYAPPID/scores/?fields=user', function(response) {

for (var i = 0; i < response.data.length; i++){
var grabbedarray = response.data[i].user.id;
console.log(grabbedarray);
}

})


The call
FB.api('/MYAPPID/scores/?fields=user'
returns a data set that has "name" and "id" properties for each element in the array, but I'm only interested in storing the "id" parts of the array.

The above code iterates through the response from the call, it checks
user.id
in each row of the array, and then the console.log shows the id for that row. This means that
var grabbedarray
is appearing several times in the console, showing a different id each time. I understand why this is happening, but I'm trying to get all the ids stored into one array, and then I'd like to console.log that.

So the final result in the console should be something like:

[456345624, 256456345, 253456435727, 376573835, 2652453245]


I've tried changing the call to
FB.api('/MYAPPID/scores/?fields=user.id'
in the hope that the response will show only a list of ids, but it's not working.

Does anyone have any idea how to solve this problem?
Thank you in advance!

Answer Source

To keep the approach you were using, you can push each new id you find into an array you define outside of the for loop.

var idArray = [];    
FB.api('/MYAPPID/scores/?fields=user', function(response) {
  for (var i = 0; i < response.data.length; i++){
    idArray.push(response.data[i].user.id);    
  }
  console.log(idArray);
})

You could also use map to transform the response array into what you want.

var idArray = [];
FB.api('/MYAPPID/scores/?fields=user', function(response) {
  idArray = response.data.map(function(x){ return x.user.id });
  console.log(idArray);
})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download