Tallying the number of messages on Facebook

Greetings everyone! I have been utilizing the Facebook JS SDK to retrieve the number of messages sent. Below is the code snippet:

<script>
  function statusChangeCallback(response) {
    console.log('statusChangeCallback');
    console.log(response);

    if (response.status === 'connected') {
      testAPI();
    } else if (response.status === 'not_authorized') {
      document.getElementById('status').innerHTML = 'Please log into this app.';
    } else {
      document.getElementById('status').innerHTML = 'Please log into Facebook.';
    }
  }

  function checkLoginState() {
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  window.fbAsyncInit = function() {
    FB.init({
      appId: '289533237896176',
      cookie: true,
      xfbml: true,
      version: 'v2.0'
    });
  };

  (function(d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
  }(document, 'script', 'facebook-jssdk'));

  function testAPI() {
    console.log('Welcome! Fetching your information.... ');
    FB.api('/me/inbox?limit=50', function(response) {  
      for (var i = 0; i < response.data.length; i++) {
        var thread = response.data[i];

        for (var j = 0; j < thread.comments.data.length; j++) {
          var comment = thread.comments.data[j].message;

          console.log(comment);
        }
      }
    });

  }
</script>

<fb:login-button scope="public_profile,email,read_mailbox" onlogin="checkLoginState();"></fb:login-button>

<div id="status">
<div id="fb-root"></div>
</div>

This successfully retrieves the messages. However, my goal is to determine the number of messages sent. I attempted using comment.length but it did not work. I am looking to find the total number of messages sent.

Below is a link to my JSON object: http://pastebin.com/dnc9U4zN

Is it possible to achieve this using the JS SDK? Any assistance would be greatly appreciated. Thank you!

Answer №1

obj represents your JSON object:

let totalComments = 0;

obj.data.forEach((post) => {
    post.comments.data.forEach((comment) => {
        totalComments++;
    });
});

console.log(totalComments);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

steps for setting up an endless scroll masonry grid

I have incorporated masonry js to display content on my website. Now, I am interested in adding infinite scrolling functionality using this script. I came across a demo that showcases this feature. However, I am struggling to figure out how to implement ...

The plugin needed for the 'autoprefixer' task could not be located

Starting out in the world of Angular 2 development can be overwhelming, especially when trying to integrate with the Play framework on the back-end side. I recently came across a helpful post by Denis Sinyakov that walks through setting up this integratio ...

How can I retrieve my array state in a different router page using VUEJS and VUEX?

I have created a page with two routes - one for the home page and another for the configuration where users can decide what content should be displayed on that container. In the configuration panel, I was able to retrieve input values and stored them in my ...

Tips for choosing option values from the browser console in Angular

Is there a way to choose one of the list values directly from the browser console? I appreciate any assistance provided <select style="width: 100%" id="Select1" class="css-dropdowns ng-not-empty ng-dirty ng-valid ng-valid-required n ...

Looking for a drag-and-drop solution using Vanilla Javascript, no need for jQuery

Looking for assistance with creating a click-and-drag solution for a background image using Vanilla Javascript. I came across a jQuery solution on Codepen, but I need help translating it into Vanilla Javascript. Draggable.create(".box", { ...

Positioning the label for a Material-UI text field with an icon adornment when the shrink property is set

https://i.stack.imgur.com/E85yj.png Utilizing Material-UI's TextField, I have an Icon embedded within. The issue arises when the label "Your good name here" overlaps the icon instead of being placed beside it. This problem emerged after I included ...

Comparison of Angular.js formsets to Django's formset

Within Django, formsets allow for the use of multiple forms within one larger form. For example, you can add multiple books to a library formset by repeating the same book form with details such as author and title. I am looking to achieve similar functio ...

Ways to showcase the content of a page once the controller variables have been set

As someone who is just starting out with AngularJS and web development, I am curious to know if there is a way to delay the display of a page until after all of the controller's $scope variables have been initialized. Most of my $scope variables are c ...

The functionality of the submit form is encountering issues upon integration of Ajax requests

Hello everybody! I am currently creating a dynamic form for editing specific classes, but I am facing an issue with the ajax call not working. Below is the HTML code for the form: <form id="userDataForm" name="userDataForm" th:acti ...

Customizing multi select in MUIv5 AutoComplete feature

My current challenge involves using the mui Autocomplete multi-select component. I'm having trouble getting it to function according to my specific requirements. Essentially, I need to set default selected values passed as props from the Parent compon ...

What is the best way to retrieve the current value of a React useState hook within a setInterval function while using Highcharts

import Error from 'next/error' import React, { useState, useEffect } from 'react' import Highcharts from 'highcharts' import HighchartsReact from 'highcharts-react-official' function generateChart() { const [co ...

Regenerate main JavaScript files in Gulp whenever partials are edited

In my gulp task for javascript files, I included partial js files in the source and filtered them out to avoid building them unnecessarily. gulp.task("js", () => { return gulp .src([ src_js_folder + "*.js", src_js_f ...

Contrasting the Next 12 client-side routing with the Next 13 server-centric routing

According to the Next 13 documentation, it explains how the new router in the app directory utilizes server-centric routing to align with Server Components and data fetching on the server. Unlike the traditional pages directory that employs client-side r ...

Module for Node.js that handles .ini files where variable names can begin with a number

.ini file: [1] 10X=true [2] 10X=true node.js : var mS = ini.parse(fs.readFileSync(__dirname + '/XXX/MS.ini', 'utf-8')); console.log(mS.1.10X); I am utilizing the ini module in node.js, which can be found at this link: https://www.n ...

What is the best approach for managing multiple HTTP requests in my specific situation?

I have a query about handling multiple HTTP requests in my code to ultimately get the desired result. Here is an outline of my approach: var customer[]; var url = '/api/project/getCustomer'; getProject(url) .then(function(data){ ...

Iterate over the array and show the elements only when a click event occurs

I am trying to create a loop through an array (array) and display the elements one by one only after clicking a button (bt). However, when I run this code, it only shows the last element of the array (i.e. honda). Can someone please help me fix this issu ...

AngularJS - Establishing communication between controller and view

I am facing an issue with the Angularjs view. I seem to be making a mistake somewhere and I can't figure out where the problem lies. I hope someone can assist me with this. The problem is that {{user.login}} (userRepoInfo.html file) is not being call ...

Is there a way to conceal the contents of a page until all the images have finished loading?

I'm currently working on improving the performance of a website that is loading very slowly. I have already reorganized, compressed and minified the JavaScript and CSS files, but the main issue seems to be with the images. The site contains large imag ...

NodeJS process that combines both client and server functionality

Attempting to develop a test echo server with both client and server in the same node process. When the code is split into two files (server and client), it functions correctly, but when combined into one file, it fails. How can I make it work within a sin ...

Combine arrays if the objects inside them are identical

Is anyone online? I need help. I have an array structured like this. var array = [ { roomNumber: 'R01', roomType: 'Deluxe', basic_facilities: 'Hot Water', additional_facilities: 'Iron' }, { roomNumber: 'R01 ...