Create a function that outputs an array containing objects as its elements

Struggling with this one, I've hit my head against all corners but something seems to be missing.

Details

I'm working on a small JavaScript page that retrieves a Facebook photo ID, calculates the total number of people who shared it, identifies the individuals who shared it, finds the number of likes for each share, and associates them accordingly. Essentially, it's a "Calculate Shared Likes" feature.

So far, I've been able to fetch the total shares and their respective likes. However, there's an issue with arrangement due to the fact that obtaining shares requires a separate FB.API call than fetching likes.

Objective

My aim is to capture the shared image ID (used for retrieving total likes), person's name, person's ID, and store them as objects within an array. Following this, I plan to loop through the array, append the like count while ensuring they match the correct person ID.

Ultimately, my final data array should consist of entries structured like:

[{"id": "pageID_PostID", "name": "Some Name", "idmin": "This is the person ID", "likes": "Total number of likes"}, {etc}, {etc}]

Challenge

The issues I'm facing are as follows:

  1. Even though I have globally defined the array, pushing objects to it outside the setting function results in an empty array upon logging. Conversely, logging inside the function displays the expected elements.
  2. Integrating the getLikes function along with finding shares causes inconsistency or undefined responses due to differing FB.api calls and delays in result retrieval.
  3. Since the goal is to present the data neatly within an HTML structure, arranging the outcome as an array of objects is necessary for easier handling without causing confusion.

CODE

var pageAccessToken;
var shares = [];

function getShares(id) {
    // Function logic here
}

function getLikes(pageID, idmin) {
    // Function logic here
}

for (var i = 0; i < shares.length -1; i++) {
    getLikes(shares[i].id, shares[i].idmin);
}

getShares(<i>insert a photo ID here</i>);
console.log("Outside call for shares array: " + JSON.stringify(shares));

Answer №1

When using the FB.api function, keep in mind that it is asynchronous and may take some time to respond. It's best to approach your function asynchronously as well. Instead of directly returning the shares variable, consider passing a function as a parameter in your getShared function. Call this function with shares as a parameter when you are ready to proceed. Here's an example:

function getShares(id, callback) {
    FB.api('https://graph.facebook.com/' + id +'/sharedposts?access_token='+pageAccessToken, function(response) {
        // ...process the response and store the result in a variable named shares...

        callback(shares); // call the passed function with "shares" as a parameter
    }
}

Next, you can invoke the getShares function by passing another function as a parameter defining what you want to do with the result:

getShares(some_id, function(shares) {
    alert('shares: ' + JSON.stringify(shares));
}

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

Angular export interface - it's like two worlds colliding

I am relatively new to coding and recently inherited a project from a former colleague who has since moved on. There seems to be an issue in the code that they left behind which is causing unexpected behavior. Below are 4 interfaces.ts files: 1. interfac ...

Is the indigo-pink color scheme fully implemented after installing @angular/material and scss using ng add command?

After running ng add @angular/material, we are prompted to choose a CSS framework and theme. I opted for indigo-pink and scss. Will the material components automatically inherit this theme, or do we need to take additional steps? When using normal CSS (wi ...

How to utilize DefinePlugin in Webpack to pass NODE_ENV value

I am attempting to incorporate the NODE_ENV value into my code utilizing webpack through the use of DefinePlugin. I have reviewed a similar inquiry on Stack Overflow, but I am still encountering issues. Here is the configuration I am working with: In pac ...

Enhancing JSON array in JMeter with the power of Groovy

In need of extracting a Non-Zero Account Number from the Accounts array provided in the JSON below. The Accounts have been successfully fetched and stored in a variable. { "glossary": { "title": "example glossary", ...

Different methods to handle form data sent via AJAX in C# programming

I'm working on a project and I've created this javascript code snippet: $(document).ready(function(){ $("form").submit(function(){ var form = $("form").serialize(); $.ajax({ type:"post", ...

"Double the explosion of strings through an array with a foreach loop

I was working on some code and here is what I have: $sample = '5ml milk, 5ml water, 3pcs carrots'; echo $sample."</br>"; $first_slice = explode(',',$sample); foreach($first_slice as $key => $value) { $second_slice[$key] = e ...

Handling mousewheel events for child elements and their parent element

I developed a custom jQuery plugin that replaces the default scrollbar with my own, managing mousewheel and bar dragging events. The issue arises when I place content containing my custom scrollbar within another content also using my scrollbar. When I sc ...

evaluating each element in a list against another

I'm attempting to check if an element exists in another list, but the lists are not in order and they are of different sizes. let list1 = [10 , 4 , 5] let list2 = [4 , 5] I attempted a solution, however it only works when the elements are in the same ...

Javascript: A guide on passing an object through multiple nested functions

Hey fellow developers, I'm facing a challenge in my code and seeking advice from the experts out there. I'm attempting to retrieve JSON data from a specific URL, as shown below, and utilize it in a React component outside of the getWeather() fun ...

Learn how to display a "not found" message in a React.js application

I have a piece of code where I am sending a post request to an API and retrieving all the data from the API in a table. I am trying to find currency data based on the currency name, if found I display the data in a div, if not found I want to print "not ...

The graph visualization fails to update properly even after attempting to redraw it

A new feature has been added to the website that allows users to zoom into specific areas of graphs created using Flot objects. An array containing all the Flot objects on the screen has been implemented, and the selection plugin is being used for this pur ...

Testing Redirects with Protractor and Jasmine: Strategies and Best Practices

Currently, I am in the process of creating a series of end-to-end tests using Protractor and Jasmine. I began by writing the following test: describe('app login page', function() { it('should be redirected to /#/login', function() { ...

Creating a component in Vue to showcase Axios, based on a straightforward example from the documentation

I apologize in advance for what may seem like a trivial question, but I assure you that I have put in a considerable amount of effort to solve this problem without success. In my appService.js file, I am making an API call as follows: import axios from &a ...

What is the process for customizing the turborepo build command to selectively recompile a particular Next.js application in accordance with the most

Seeking guidance on integrating turborepo with Next.js. In my repository's apps folder, I have two applications named web and docs. Despite deploying them separately on Vercel, an issue arises every time I commit changes to the web application - both ...

What is the best way to pass the value of a selected option to an express server

<label for="exampleFormControlSelect1"> <strong>Please Select the Number of PDFs to Merge:</strong> </label> <select class="form-control" id="exampleFormControlSelect1"> <option name=" ...

Is there a way to update a single document in a MongoDB database using Mongoose without directly referencing the document?

Let's say I have an example: 1 //Let's say I have an example 2 3 app.post('/update', validate, async (req, res) => { 4 const {title, description, post_id} = req.body; 5 6 // Updating one of them if they exist 7 ...

Show the "Splash" picture, then switch to a newly uploaded image and show it for a set amount of time

I am in the process of developing an HTML/JavaScript page that will showcase a splash image (splash.jpg) until it gets replaced by another image file called latest.jpg. Once this latest.jpg is displayed, I want it to remain on the screen for 90 seconds bef ...

Issue encountered while requesting data from API in ReactJS

I've been trying to fetch data from using the react useEffect hook. However, instead of displaying the data, I keep getting an error message that says, "Error: Objects are not valid as a React child (found: object with keys {number, name}). If you me ...

Another option for document.execCommand('selectAll',false,null)

I've come across a piece of code that allows me to select the text in a div whenever a user clicks on it: <table> <tr> <td> <div contenteditable onClick="document.execCommand('selectAll',false,null)">I& ...

capture the alteration of text within an input field

Currently, I am utilizing the Joomla calendar feature to select a date. The HTML code for this functionality is displayed below. When you click on the image, a calendar will pop up allowing you to choose a date. Once selected, the popup closes and the date ...