P
P
Pavel Chuev2015-10-01 16:52:37
JSON
Pavel Chuev, 2015-10-01 16:52:37

How to execute a condition if there is at least one true condition in the JSON array?

The array looks something like this:

[{"ui_bid":"1451245124","ui_id":"124161616"}{"ui_bid":"124124124","ui_id":"123124"}{"ui_bid":"0","ui_id":"12123124"}{"ui_bid":"0","ui_id":"1231242352"}]

the following code only pulls the last ui_bid equal to zero
function Request() {
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var responseBody = xhr.responseText;
            var event = JSON.parse(responseBody, function(key, value) {
                if (key == 'ui_bid')
                    return value;
                if (value != '0') {
                    xhr.open('GET', 'тут url для запроса', false);
                    xhr.send();
                    setTimeout(UpdateInventory, 60000);
                }
            })
        }};
    xhr.open('GET', 'тут тоже url для запроса', false);
    xhr.send();
}
Request();

how to rewrite the code so that at least one ui_bid is not equal to zero in the array, the required request is executed?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Ineshin, 2015-10-01
@AllDecay

I would write like this, everything works: jsfiddle.net/oay5jcna

var data = JSON.parse('[{"ui_bid":"1451245124","ui_id":"124161616"},{"ui_bid":"124124124","ui_id":"123124"},{"ui_bid":"0","ui_id":"12123124"},{"ui_bid":"0","ui_id":"1231242352"}]');

data.forEach(function (item, value) {
    var bid = +item.ui_bid;
    
    if (bid) {
        console.log(value); // Вот тут ваш запрос
    }
});

Apart from that, I would also abstract XHR into a separate class so that normal instances can be created.

V
Vitaly Inchin ☢, 2015-10-01
@In4in

var acess = array.some(function(e){
  return +e.ui_bid === 0;
}); 

//acess = true, если хоть 1 из ui_bid равен 0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question