Selecting the most popular post from a Facebook group

Here is the JSON file that I am currently using JSON.parse(); in Google Apps Script. Currently, I have found a temporary solution with this code by selecting posts that have more than 15 likes. However, my goal is to be able to select the post with the most likes regardless of whether it has more than 15 likes or not.

function repost() {
var UsrAccess_token = "xxxxxxxxx"
var graph = "https://graph.facebook.com/xxxxxx/feed/?access_token="+UsrAccess_token+"";
var jsondata = UrlFetchApp.fetch(graph,{method:"get"}).getContentText();
var object = JSON.parse(jsondata);
var item = object.data;
var currentTime = new Date();
var year = currentTime.getUTCFullYear();
var month = (currentTime.getUTCMonth()) + 1;
var day = (currentTime.getUTCDate()) - 1;
if (day <= 9) {var day = "0"+day+"";}
if (month <= 9) {var month = "0"+month+"";}
var utime = ""+year+"-"+month+"-"+day+"T";
try {
var i = null;
for (i = 0; item.length > i; i += 1) {
var pubDate = item[i].created_time;
if (pubDate.match(utime)) { var likesdata = item[i].likes.data; var len = likesdata.length;
                           if (len > 15) {var popular = item[i].link;}}


}} catch(err) {
   var err = "ERROR";
}
}

Answer №1

To set a default value for a variable, you can use something like var maxLikes = 0; and compare it with the len variable.

An example of the code would look like this:

function repost() {
var UsrAccess_token = "xxxxxxxxx"
var graph = "https://graph.facebook.com/xxxxxx/feed/?access_token="+UsrAccess_token+"";
var jsondata = UrlFetchApp.fetch(graph,{method:"get"}).getContentText();
var object = JSON.parse(jsondata);
var item = object.data;
var currentTime = new Date();
var year = currentTime.getUTCFullYear();
var month = (currentTime.getUTCMonth()) + 1;
var day = (currentTime.getUTCDate()) - 1;
if (day <= 9) {var day = "0"+day+"";}
if (month <= 9) {var month = "0"+month+"";}
var utime = ""+year+"-"+month+"-"+day+"T";
try {
  var i = null;
  var maxLikes = 0; 
  for (i = 0; item.length > i; i += 1) {
    var pubDate = item[i].created_time;
    if (pubDate.match(utime)) { 
      var likesdata = item[i].likes.data;
      var len = likesdata.length;
      if (len > maxLikes) {
        maxLikes = len;
        var popular = item[i].link;
      }
    }
  }
} catch(err) {
   var err = "ERROR";
}

}

I hope this explanation is helpful!

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

Importing a hierarchical JSON file into a MySQL database

I'm facing an issue with parsing a JSON file into a MySQL database. The file is an export of Facebook stats for multiple pages. Since I have exports from different pages, it's crucial to have the corresponding ID in the database. The structure ...

Google Chrome extension with Autofocus functionality

I developed a user-friendly Chrome extension that allows users to search using a simple form. Upon opening the extension, I noticed that there is no default focus on the form, requiring an additional click from the user. The intended behavior is for the ...

Grok is failing to generate properly formatted JSON output

When analyzing the following log line, an issue with invalid JSON for the grok pattern was discovered. 2021-06-15 10:05:55:617|[28]|test-backend|ERROR|STDOUT|test|test-service|abcd1234|API_CALL|test|Error|Controller {"testtag":["test error ...

The problem with JQuery ajax arises when attempting to send a file input value

I am facing an issue when trying to send a file value to PHP using the ajax code below. The file gets uploaded successfully and stored in the database, but the problem arises when I get redirected. // form data submission $('#myForm').submit(fun ...

In PHP, when an array value is empty, replace any null references with empty quotes in JSON

Is there a way to remove the value "null" from empty array values? I recently added this code snippet to convert the JSON format: for( $cnt=0; $cnt<$iNumberOfPics; $cnt++ ) { $output[]=array('video_img_url'=>$img[$cnt],'video_u ...

Need help with updating React component state within a Meteor.call callback?

I've constructed this jsx file that showcases a File Uploading Form: import React, { Component } from 'react'; import { Button } from 'react-bootstrap'; class UploadFile extends Component { constructor(){ super() this. ...

Utilize Node.js v16 for the execution of chaincode operations

Currently, I am executing JavaScript/TypeScript chaincode from fabric-samples (asset-transfer-basic/chaincode-javascript) and my requirement is to switch the Node.js version from 12 to 16. I suspect that the hyperledger/fabric-nodeenv image is specifying ...

Issue encountered: React module not detected while attempting to execute npm start command

While developing my react app, I encountered an issue when trying to run 'npm start'. The application was working as expected until I faced a bug that prompted me to update my node version for a potential fix. After upgrading to node v16.13.2 and ...

What is preventing me from accessing the variable?

Having some trouble using a variable from JSON in another function. Can someone lend a hand? async function fetchData() { let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d'); let data = await response.js ...

Tips for using Jquery to round up currency values

Is there a way to round up various currencies using jQuery? I have a specific requirement: 10.30 → 10 //Round down if below .5 10.60 → 11 //Round up if after .5 849.95 → 850 1,022.20 → 1022 ...

Generating a fresh object from an existing object by incorporating updated values using Angular and Ionic version 3

Currently, I am actively working on an Ionic 3 project that utilizes Angular framework. Within my project, I have a JSON object called 'person' which consists of data fields such as name, job, and home. One feature in my app is an Ionic toggle b ...

Tracking Time Spent in a Tab using HTML and JavaScript

I have a unique issue that requires a specific solution. Despite my extensive search across the internet, no useful answers were found. This is the snippet of HTML code in question: <form action="/timer.php" method="POST"> <span>Fir ...

"Exploring the power of NodeJS with createServer, dealing with

Can instances of global.request potentially collide in this NodeJS scenario? I have a basic web server set up in NodeJS where I am globally exposing the request that is created: http.createServer(function(req, res) { global.request = req; // do ...

Tips for implementing events with AngularJS Bootstrap Colorpicker

I am having trouble understanding how events function with Angular Bootstrap Colorpicker. I have forked a Plunker from the developer's example. Unfortunately, there are no examples provided for using events. It would be great if events like colorpick ...

Input information into the system from the successful response found on a different page

After receiving my ajax response successfully, I want to redirect to a new aspx page where there are 30 input type text controls. My goal is to populate all the values in those controls. How can I achieve this? Any suggestions? This is what I have attempt ...

Navigating the ropes of push-pull functionality in Bootstrap 5

How can I utilize push and pull in Bootstrap version 5.0.0-beta2? In Bootstrap 3, my code looks like this: <link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet" /> <div class="row"> <d ...

Decode a date and fetch it in the desired format within the ajax success function

Hey there, I've encountered an issue in retrieving the date value in ajax success. Can someone guide me on how to fix this problem? $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", data: {}, ...

Using JSON.NET in C# to decode Twitter JSON and retrieve hashtags

Perhaps I am posing this question again, but this is my first attempt and I haven't come across anything quite like my situation.. As I code in C# and utilize JSON.NET to deserialize a JSON, the JSON file is retrieved from Twitter as a response to ...

What could be causing my Express server to return a 404 error when trying to submit the form, all while failing to display any console

Having trouble setting up multi-user sessions similar to Google Docs, but my server file seems unresponsive. I've double-checked my fetch function and ensured it is accurate, yet no changes are occurring. Even console.logs from the server file command ...