JavaScript对象结构问题

时间:2017-01-24 02:35:55

标签: javascript jquery javascript-objects for-in-loop

我在遍历从上传的文件数据返回的对象时遇到问题,但似乎可能正在返回的对象结构阻止我从响应中的每个对象捕获特定属性,或者我错误地解释了如何我应该访问这个对象。当我记录data.length时,我得到995,我假设它是对象响应中的字符数。当我记录data[prop]时,它会记录每个角色。

这是我返回的文件对象数据:

[
  {
    "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请求上传文件并将对象返回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));
            }
        });

3 个答案:

答案 0 :(得分:2)

data是一个JSON字符串,您必须使用JSON.parse将其解析回对象数组,如下所示:

success: function(data){
    var arr = JSON.parse(data);

    // use arr as array
    console.log(arr.length);
    // arr[0] is the first object
}

答案 1 :(得分:1)

它只是JSON格式的字符串。您需要JSON.parse转换为JS对象,或使用$.getJSON()

答案 2 :(得分:0)

假设您要访问第一个fieldname,可以通过data[0].fieldname方式访问它。第二种情况也是如此:data[1].fieldname。为什么?因为您的数据解释如下:

0: {"fieldname": "fileUpload", ...}, 1: {"fieldname": "fileUpload", ...}