JavaScript似乎无法访问对象属性

时间:2018-01-04 20:45:49

标签: javascript javascript-objects

所以我有这个对象,看起来像这样: enter image description here

我正在尝试访问when_is_meeting属性。我没有任何问题访问此对象中的任何其他属性。但是,如果我尝试访问when_is_meeting,我会看到undefined,如上所示"当它是"

这就是代码的样子......

var listOfObjects = [];
    for (var modelData in responseData) {
        listOfObjects.push(service.create(name, responseData[modelData]));
        console.log('RESP', response.data.content[modelData]);
        console.log('WHEN IS IT!!!',response.data.content[modelData].when_is_meeting);
    }

有谁知道这里到底发生了什么?我拼错了吗?我已经过了50次。必须是简单易懂的东西。

----------------编辑------这里是整个服务------------------- ---

    service.fetch = function (name, id, options) {
    options = options || {};
    const ModelClass = service.models[name];
    const baseUrl = ModelClass.getUrl(service.getBaseUrl(ModelClass), ModelClass.getModelName());
    let url;
    let paged = false;
    let pageList = false;


    if (id) {
        if (id instanceof models.BaseModel) {
            const BaseModelModelName = id.getModelName();
            let baseModelWithId = ModelClass.getUrl(service.getBaseUrl(), BaseModelModelName);
            url = [baseModelWithId, id.getId(), ModelClass.getModelName(), ''].join('/');
            pageList = true;
        } else {
            url = [baseUrl, id].join('/');
        }
    } else {
        pageList = true;
        url = [baseUrl, ''].join('/');
    }

    if (options.path) {
        url = url + options.path;
        delete options.path;
    }

    if (typeof options.paged === 'object') {
        let currentPage = options.paged.page;
        let pageSize = options.paged.page_size || 20;
        paged = options.paged;
        options.page = currentPage;
        options.size = pageSize;

        if (options.paged.sort) {
            let sortParam = options.paged.sort;

            options.sort = sortParam.param+','+sortParam.order;
        }

        delete options.paged;
    }

    return AuthRequestsService.load.then(function () {

        return $http({
            method: 'GET',
            url: url,
            headers: {
                'Authorization': AuthRequestsService.getAuthorizationHeader(),
            },
            params: options,
            json: true
        });
    }).then(function (response) {
            console.log('RESPONSE',response);
            for (let i = 0; i < response.data.content.length; i++){

              if (response.data.content[i].activity_history_type == 3){

                let builder = JSON.parse(response.data.content[i].relations);
                let secondaryUrl = AppSettings.apiUrl + ['/advisor/meetings', builder.meeting].join('/');

                $http({
                    url: secondaryUrl,
                    headers: {
                        'Authorization': AuthRequestsService.getAuthorizationHeader(),
                    },
                    method:'GET',
                    json:true,

                }).then(function(res){
                   response.data.content[i].when_is_meeting = res.data.meeting_date;
                   console.log('WHEN IS',response.data.content[i].when_is_meeting); // <-- this works
                })
              }
            }
            if (!pageList) {
                return service.create(name, response.data);
            } else {
                let responseData = response.data;
                if (paged) {
                    responseData = response.data.content;
                }

                var listOfObjects = [];
                for (var modelData in responseData) {
                    listOfObjects.push(service.create(name, responseData[modelData]));
                    console.log('RESP', response.data.content[modelData]);
                    listOfObjects[modelData].when_is_meeting = response.data.content[modelData].when_is_meeting;
                    listOfObjects[modelData].whatever = 44;
                    console.log('response.data.content[modelData].when_is_meeting',response.data.content[modelData].when_is_meeting);
                    console.log('listOfObjects[modelData].when_is_meeting', listOfObjects[modelData].when_is_meeting);
                    console.log('listOfObjects[modelData].whatever', listOfObjects[modelData].whatever);
                    console.log('Keys', Object.keys(response.data.content[modelData]));

                    // console.log('PRE IF', response.data.content[modelData].when_is_meeting);
                    // listOfObjects[modelData].when_is_meeting = response.data.content[modelData].when_is_meeting;
                    // console.log('IFFFFFFFFFFFFFFFFFFFFF', listOfObjects[modelData].when_is_meeting);
                    // console.log('IN FOR LOOP RESP', response.data.content[modelData].when_is_meeting);
                    // console.log('listOfObjects[modelData] PART 2', listOfObjects[modelData]);
                    function testForKey() {
                        if (typeof response.data.content[modelData].when_is_meeting !== "undefined") {
                            // when_is_meeting now exists! Do stuff with it here.
                            console.log("We now have the key:", response.data.content[modelData].when_is_meeting)
                        }
                        else {
                            // when_is_meeting is still missing. Try again in 200ms.
                            window.setTimeout(testForKey, 200);
                            console.log('TTTIIMMMEEEEOOOUUUTTT');
                        }
                    }
                    testForKey();
                }


                if (paged) {
                  console.log('#########################', listOfObjects);
                    return {
                        objects: listOfObjects,
                        totalPages: response.data.totalPages,
                        currentPage: response.data.number,
                        isMore: (!response.data.last),
                        totalElements: response.data.totalElements
                    };
                } else {
                    return listOfObjects;
                }
            }
    });
};

enter image description here

1 个答案:

答案 0 :(得分:2)

出现此问题是因为当您展开切换按钮以查看对象时,控制台会显示现在的内容,而不是记录时的内容。

这里解释得很好:http://felix-kling.de/blog/2011/08/18/inspecting-variables-in-javascript-consoles/

使用Ajax时,这种情况并不少见。您正在尝试在所有内容完成之前访问结果;即,代码中的其他内容正在您的response.data上工作,并在console.log语句后添加缺少的密钥。

@Steven在上述评论中建议的日志记录声明证实了这一点。 Object.keys(response.data.content[modelData]))将显示日志语句生成时可用的键,因此不会出现与将对象本身记录到控制台相同的问题。确认when_is_meeting的结果在对数时确实丢失了。

要正确解决此问题,我们需要查看更多代码,以便我们可以找出为什么在其他内容完成使用之前尝试访问您的结果。

或者,您可以使用超时来测试response.data.content[modelData] when_is_meeting的可用性,并仅在存在时访问它,如下例所示。但这并不是真的建议 - 更好地找出问题在你的响应处理中的位置。

var listOfObjects = [];
for (var modelData in responseData) {
    listOfObjects.push(service.create(name, responseData[modelData]));

    // testForKey looks for the required key 'when_is_meeting' and if it does not
    // exist it starts a timeout to test for it again in the future.
    function testForKey() {
        if (typeof response.data.content[modelData].when_is_meeting !== "undefined") {
            // when_is_meeting now exists! Do stuff with it here.
            console.log("We now have the key:", response.data.content[modelData].when_is_meeting)
        }
        else {
            // when_is_meeting is still missing. Try again in 200ms.
            window.setTimeout(testForKey, 200);
        }
    }
    testForKey();
}

(我没有测试过这段代码 - 它可能有语法错误)

更新 - 修复了您提供的代码

您提供的代码显示正如预测的那样,when_is_meeting密钥将在单独的Ajax调用中添加到您的结果中。此调用以异步方式完成,因此其结果不可用于其下方的日志语句。该片段显示了一种修复它的方法。和以前一样,我没有语法检查过这段代码。

return AuthRequestsService.load.then(function () {
    return $http({
        method: 'GET',
        url: url,
        headers: {
            'Authorization': AuthRequestsService.getAuthorizationHeader(),
        },
        params: options,
        json: true
    });
}).then(function (response) {
    console.log('RESPONSE',response);
    for (let i = 0; i < response.data.content.length; i++){

      if (response.data.content[i].activity_history_type == 3){

        let builder = JSON.parse(response.data.content[i].relations);
        let secondaryUrl = AppSettings.apiUrl + ['/advisor/meetings', builder.meeting].join('/');

        // Store the result of this $http call as a promise.
        response.data.content[i].when_is_meeting_promise = $http({
            url: secondaryUrl,
            headers: {
                'Authorization': AuthRequestsService.getAuthorizationHeader(),
            },
            method:'GET',
            json:true,

        })
        // Remove your .then handler from here. It will be dealt with below.
        //.then(function(res){
        //   response.data.content[i].when_is_meeting = res.data.meeting_date;
        //   console.log('WHEN IS',response.data.content[i].when_is_meeting); // <-- this works
        //})
      }
    }
    if (!pageList) {
        return service.create(name, response.data);
    } else {
        let responseData = response.data;
        if (paged) {
            responseData = response.data.content;
        }

        var listOfObjects = [];
        for (var modelData in responseData) {
            // OK, now access the promise you stored above. This means you'll be sure you'll
            // have the when_is_meeting key.
            responseData[modelData].when_is_meeting_promise.then(function(when_is_meeting_result) {
                // Now you can copy the neeting date into your responseData object.
                responseData[modelData].when_is_meeting = when_is_meeting_result.data.meeting_date;

                // Carry on....
                listOfObjects.push(service.create(name, responseData[modelData]));
                console.log('RESP', response.data.content[modelData]);

                // This should now work...
                console.log('response.data.content[modelData].when_is_meeting',response.data.content[modelData].when_is_meeting);
            });
        }
    }
});