延迟对象中的jquery $ .grep返回无法读取属性' value'未定义的

时间:2018-02-07 16:22:14

标签: jquery ajax grep each jquery-deferred

我在尝试使用$ .grep

获取值时遇到问题

我向网址发送GET请求,以便将日期和值的大量数据作为JSON。

然后在回调函数中,我从JSON文件中获取日期和值,并使用延迟对象将结果赋值给变量。

ajax请求完成后,我遍历原始响应,然后使用$ .grep过滤json变量以获得正确的值。

如果我在console.log中获得$ .grep的结果,我会得到正确的值,但是我得到了以下错误。

  

jQuery.Deferred exception:无法读取属性' value'未定义的   TypeError:无法读取属性' value'未定义的

如何从$ .grep中获取值?

var history;

$.getJSON(window.website_url + 'history', function(response) {

    var series = { 
        name: 'Price Index History', 
        data: []
    };

    var deferreds = [];

    if($('#currency').val() === 'GBP') {

        deferreds.push(
            $.ajax({
                url: window.website_url = 'exchange-rate',
                type: 'get',
                dataType: 'json',
                success: function (data) {
                    history = data;
                }
            })
        );

        $.when.apply($, deferreds).done(function() {

            $.each(response, function(i, item) {

                var date = new Date(item[0]),
                    day;

                if((date.getMonth() + 1) < 10) {
                    day = date.getFullYear() + '-' + '0' + (date.getMonth() + 1) + '-' + date.getDate();
                }
                else {
                    day = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
                }

                var result = $.grep(history, function(e) { return e.date == day; });

                var test = result[0].value;

                series.data.push([item[0], Number(parseFloat(item[1] * result[0].value).toFixed(1))]);
            });
        });
    }
    else {
        $.each(response, function(i, item) {
            series.data.push([item[0], item[1]]);
        });
    }
});

修改

Here is the json returned the ajax request
[
    {
        "date":"2018-01-30",
        "value":0.706419
    },
    {
        "date":"2018-01-31",
        "value":0.70417
    },
    {
        "date":"2018-02-01",
        "value":0.70095
    },
    {
        "date":"2018-02-02",
        "value":0.70808
    },
    {
        "date":"2018-02-03",
        "value":0.70808
    },
    {
        "date":"2018-02-04",
        "value":0.70871},
    {
        "date":"2018-02-05",
        "value":0.717141
    },
    {
        "date":"2018-02-06",
        "value":0.71645
    },
    {
        "date":"2018-02-07",
        "value":0.716369
    }
]

1 个答案:

答案 0 :(得分:1)

我看到你的问题......

对于某月中的某些日期,例如01 - 09,getDate()将返回一位数字(即1,2,3等)。

对于2018-02-06的日期,您要将2018-02-062018-01-6

进行比较

使用此类函数将6替换为06

function day_of_month(d) { 
    return (d.getDate() < 10 ? '0' : '') + d.getDate();
}

,例如

day = date.getFullYear() + '-' + '0' + (date.getMonth() + 1) + '-' + day_of_month(getDate());