Question

I want to get all of the IDs that liked a post. So I started looping through the JSON object and thats working great. But how can I seperate the different post likes and push them into an array?

heres my code:

var posts = data.posts.data.length; // how much posts (4)    
var likedIDs = [];    

for (var i = 0; i < posts; i++) {

var likes = data.posts.data[i].likes.data.length; //how much likes the post got

    for(var j = 0; j < likes; j++){
        likedIDs.push(data.posts.data[i].likes.data[j].id); //push liked IDs into array
    }

}

my result now is:

["100002767544234", "100002240698218", "100002186226181", "661093262", "100002965256572", "100000484302816", "1328033466", "100002965256572", "100000433187588", "100001859514071", "510954562300442", "1534181150", "100000433187588", "1534181150", "100000470102176", "231605130289758", "1328033466", "661093262", "100002186226181", "100002240698218", "1007746467", "100000433187588", "1216261931", "661093262", "1313025972", "100002240698218", "1534181150", "661093262", "100000328468050", "100001350606484", "100002767544234", "100000306728917", "1534181150", "100000328468050", "1216261931", "661093262", "100002240698218", "100000502074422", "100002559952817", "100000328468050", "100000484302816", "1802439459", "100002240698218", "1328033466"]

Now every ID that ever liked the specific posts is in the array but I need them seperated by post index or in an object like this:

[["1313025972", "100002240698218", "1534181150"],["1313025972", "100002240698218", "1534181150"],["1313025972", "100002240698218"],["1313025972"]]

I need them to check if a logged in fb user already has liked the post or not.

Any ideas? thx in advance and sorry for my bad englisch

Was it helpful?

Solution

I think you want this:

[["1313025972", "100002240698218", "1534181150"],["1313025972", "100002240698218", "1534181150"],["1313025972", "100002240698218"],["1313025972"]]

instead of:

[{"1313025972", "100002240698218", "1534181150"},{"1313025972", "100002240698218", "1534181150"},{"1313025972", "100002240698218"},{"1313025972"}]

because this one is not a valid javascript object.

So if this the case do this to get what you want:

for (var i = 0; i < posts; i++) {

    var likes = data.posts.data[i].likes.data.length;
    var plikes = [];
    for (var j = 0; j < likes; j++) {
        plikes.push(data.posts.data[i].likes.data[j].id);
    }
    likedIDs.push(plikes);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top