Search code examples
javascriptjqueryjavascript-objectsfor-in-loop

JavaScript Object Structure Issue


I am having an issue traversing the objects returned from uploaded file data, but it appears that potentially the object structure that is being returned is preventing me from capturing specific properties from each of the objects in the response or that I am misinterpreting how I should be accessing this object. When I log data.length I get 995, which I assume is the number of characters in the object response. When I log data[prop] It logs each individual character.

Here is my returned file object data:

[
  {
    "fieldname": "fileUpload",
    "originalname": "Screen Shot 2017-01-08 at 12.23.39 PM.png",
    "encoding": "7bit",
    "mimetype": "image/png",
    "size": 39881,
    "bucket": "test",
    "key": "1/2017-01-23/screen-shot-2017-01-08-at-12.23.39-pm.png",
    "acl": "public-read",
    "contentType": "image/png",
    "contentDisposition": null,
    "storageClass": "STANDARD",
    "metadata": null,
    "location": "https://test.s3.amazonaws.com/1/2017-01-23/screen-shot-2017-01-08-at-12.23.39-pm.png",
    "etag": "\"sfasgltg702o\""
  },
  {
    "fieldname": "fileUpload",
    "originalname": "Screen Shot 2017-01-08 at 12.21.04 PM.png",
    "encoding": "7bit",
    "mimetype": "image/png",
    "size": 58386,
    "bucket": "test",
    "key": "1/2017-01-23/screen-shot-2017-01-08-at-12.21.04-pm.png",
    "acl": "public-read",
    "contentType": "image/png",
    "contentDisposition": null,
    "storageClass": "STANDARD",
    "metadata": null,
    "location": "https://test.s3.amazonaws.com/1/2017-01-23/screen-shot-2017-01-08-at-12.21.04-pm.png",
    "etag": "\"151353j53j51u5j135ju\""
  }
]

jQuery AJAX POST request uploading the files and returning the objects to data:

$.ajax({
            url: '/app/sign',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(data){
                console.log('upload successful! ' + data);

                console.log('Just the key ' + data.length);
                for(var prop in data){
                    console.log(data[prop]);
                }
            },
            error: function(error){
                console.log('error ' + JSON.stringify(error));
            }
        });

Solution

  • data is a JSON string, you have to parse it back to an array of objects using JSON.parse like this:

    success: function(data){
        var arr = JSON.parse(data);
    
        // use arr as array
        console.log(arr.length);
        // arr[0] is the first object
    }