0

I'm completely new at Javascript and I'm trying to stringify an array of objects photos. When I try

console.log(photos)

it gives

Photos 
[]
​
0: Object { name: "IMG_2910.jpg", path: "https://..." }
​
1: Object { name: "IMG_2911.jpg", path: "https://.." }
​
length: 2
​
<prototype>: Array []

When I try to stringify however with Json.stringify()

console.log("Photos again", JSON.stringify (photos))

I'm getting an empty array.

I understand from reading similar questions that stringify does not work on a usual array, have seen many examples though of using it on an array of objects and it works.

What could I be doing wrong here?

The photos are populated as follows:

uppy.on('complete', result => {
        if (result.successful.length > 0) {
          result.successful.forEach((element) => {
            photos.push({
              name: element.name,
              path: element.uploadURL
            });
          });
        };

      });

And the logging is done as follows:

console.log("Photos", photos);
console.log("Photos again", JSON.stringify (photos));
mrateb
  • 2,317
  • 5
  • 27
  • 56
  • Can you show us the code that builds the array of photos? – Cat Aug 23 '19 at 07:10
  • 3
    Probably `photos` is populated asynchronously (using a HTTP request for instance). The solution is to await (with promise or callback) for the data to be available and only then process it further. You need to look into asynchronous programming with JavaScript. – trincot Aug 23 '19 at 07:10
  • Thanks a lot guys, understood the problem from your comments here and the reference to the question to which mine is a duplicate :) – mrateb Aug 23 '19 at 08:16

0 Answers0