S
S
SpeakeazyYT12019-03-18 17:06:14
JavaScript
SpeakeazyYT1, 2019-03-18 17:06:14

Why does the output of the maximum value of JSON data received by the getJSON method not work?

Good evening! I have the following code:

$('#year').on('change', function() {
        $('#result').html('');
            a = [];
        var maxleng = getMax(a, "UF_LENGTH");
        $.getJSON("api.php", {
                action: "getAkb"
            })
            .done(function(data) {
                $.each(data, function(i, item) {
                    if (item.UF_TYPE == 'A') a.push(item);
                });
                if (a.length > 0) {
                    result += '<h4>Europe</h4>';
                  
                    console.log("Наибольшая длина: " + maxleng.UF_LENGTH);
                  
                    $.each(a, function(i, item) {
                        result += item.UF_LENGTH + ' x ' + item.UF_WIDTH + ' x ' + item.UF_HEIGHT + ' ' + item.UF_CAPACITY + 'Ah ' + item.UF_CAPACITY + 'EN V' + '<br>';
                    });
                }
                $('#result').html(result);
            });
    });


All that should be of interest is the maxleng variable, which is responsible for displaying the maximum value for the UF_LENGTH key in the "a" array.

getmax function:

function getMax(arr, prop) {
    var max;
    for (var i=0 ; i<arr.length ; i++) {
        if (!max || parseInt(arr[i][prop]) > parseInt(max[prop]))
            max = arr[i];
    }
    return max;
}


In .done(function(data) I put console.log("Maximum length: " + maxleng.UF_LENGTH); to print the maximum value by json key from array "a".
There was a problem when I tried to execute my script in the console I got an error: Uncaught TypeError: Cannot read property ' UF_LENGTH' of undefined What
did I do wrong in the code? {"UF_LENGTH":"3"}]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2019-03-18
@SpeakeazyYT1

So you calculated the value of the maxleng variable when the array was empty. Naturally, an empty value was returned, in which there is no UF_LENGTH field.
In addition, the UF_TYPE field is not defined in your JSON data, which means that when filtering, nothing will get into the a array.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question