Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I collect objects being sent in from another function in Javascript?

I have a function, let’s call it GetData(). I am pulling in data from a query in another function and running an ajax call to populate the data. Once that happens I then send to another function, let’s call that PlaceData(). The data is placed together in an object each time it runs through the ajax call in GetData(). I then send each object to PlaceData() and I want to collect these objects in an array in PlaceData() by the push() method but each time it just adds a new array of the current object being sent in so I just get separate objects instead of a collection. How do I get them to collect into one array?

So here is an example of code I am using:

function GetData(query) {
    var json = "";
    var api_url = ('https://jsondata.site?conn={conn}&query={query}');
    $.ajax({async: false; url: api_url, method: "GET"}).done(function(data){
        json = JSON.parse(data);
    });
    PlaceData(json);
};

function PlaceData(data) {
    var objCollect = [];
    objCollect.push(data);

    console.log(objCollect);
};

I am wanting objCollect[] to keep all objects being passed in but instead I just get a new array with each individual object

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to use a globally scoped variable to store objects. Define objCollect out of the functions and it should now hold all the values.

var objCollect = [];

function GetData(query) {
    var json = "";
    var api_url = ('https://jsondata.site?conn={conn}&query={query}');
    $.ajax({async: false; url: api_url, method: "GET"}).done(function(data){
        json = JSON.parse(data);
    });
    PlaceData(json);
};

function PlaceData(data) {
    objCollect.push(data);
    console.log(objCollect);
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading