0

I have 2 getJSON calls and, the second is dependent on the first. Based on the length of the second one, I want to push values from the first call to an array and use outside of the loop.

I know these are async calls but I need to know how to get these values inside an array and be made to use outside the loop.

First JSON:

let first_json = [
    {
        "company": "one"
    },
    {
        "company": "two"
    },
    {
        "company": "three"
    }
]

The second JSON is dependent on the first one.

Here is my getJSON code:

let arr = [];
$.getJSON(first_json, function(data) {
    data.forEach(d => {
        let second_json = json_string+d.company;
        $.getJSON(second_json, function(two_data) {
            if (two_data.length > 0) arr.push(d.company);
        });
    });
});
console.log(arr);

Right now I am getting back an empty array.

Assuming company: two is empty, arr should return ['one', 'three'].

nb_nb_nb
  • 1,243
  • 11
  • 36
  • i dont know much about jquery but general questions... – Goofballtech Jun 19 '20 at 00:26
  • you have it set as json string, then you do a forEach which would need to be on an array, then you co cat to build second_json which would need to be on a string, then you do logic on a string\array thing, then you push an unknown thing to the arr array. Might be worth checking the variable types a few times through your processes and see how thing are changing. – Goofballtech Jun 19 '20 at 00:28
  • @Goofballtech, the variable types correct. the `second_json` like the first returns an array of objects like the first one. they return results based on the company name of first_json – nb_nb_nb Jun 19 '20 at 00:30
  • @ibrahimmahrir, I am not sure, its a django based web project with ES6 and javaScript jQuery on the frontend – nb_nb_nb Jun 19 '20 at 15:48
  • @nb_nb_nb Sorry for any trouble caused, [**here is the final answer**](https://jsfiddle.net/jz31tmvh/) – ibrahim mahrir Jun 19 '20 at 16:26
  • @nb_nb_nb ... and if by any chance your environment supports `async`/`await` you can use [**this cleaner approach**](https://jsfiddle.net/z4ka3jn1/) – ibrahim mahrir Jun 19 '20 at 16:36
  • I hope it's working now, and again I'm so sorry for the inconvenience. – ibrahim mahrir Jun 19 '20 at 16:42
  • 1
    @ibrahimmahrir, no thank you so much for all your help! – nb_nb_nb Jun 19 '20 at 16:55
  • 1
    @ibrahimmahrir, Thank you again, if you put up your promise method as the answer I can pick it as the answer! it works like a charm – nb_nb_nb Jun 19 '20 at 17:00
  • 1
    You're welcome! Glad I could help. Happy coding :) – ibrahim mahrir Jun 19 '20 at 17:02

0 Answers0