简体   繁体   中英

How do I get the length of an Array when certain conditions are met?

I am attempting to print out a length when certain conditions are met after making an AJAX GET request to an API. I am unsure if I am doing it correctly. I'm not sure if you can help me but I thought I'd try since I am stuck.

The code represents when a UserID matches the LocalStorage UserID, loop through all Issues where IsClosed is False and the Issue occurred within the last 24 hours. Also, the isAfter is not working either. Can anyone make a suggestion for that too?

Also, please let me know if you need me to provide any additional information. Thank you.

function showNotificationCount(isLive, userIDNum, baseURL) {
  var userIDLogin = localStorage['userIDNum'];
  var userFullName = localStorage['userName'];
  // var webMethod = isLive ? 
  $.ajax({
    type: "GET",
    url: webMethod,
    contentType: "application/json; charset=utf-8",
    dataType: "JSON",
    data: {
      userID: userIDNum
    },
    success: function(data) {
      var parsedData = JSON.parse(data);
      var twentyFourHoursAgo = moment().subtract(1, 'day');
      console.log(parsedData);
      if (userIDLogin == userIDNum) {
        $.each(parsedData, function(index, item) {

          // # of open issues
          if (item.IsClosed == false) {
            if (moment(item.CreatedDate).isAfter(twentyFourHoursAgo)) {
              var openIssues = parsedData.length;
              console.log(openIssues);
              $('.openIssueCount').html(openIssues);

            }
          }

        });
      }

    },
    error: function(xhr, status) {
      console.log(xhr.responseText);
      console.log(xhr.status);
    }
  });
}

Here is some example code to show what I was saying in the comment. I make no claim this is correct -- it is show EXACTLY what I tried (and failed) to describe in english above.

var hiImAcounter;

hiImAcounter = 0;

$.each(parsedData, function(index, item) {

      // # of open issues
      if (item.IsClosed == false) {
        if (moment(item.CreatedDate).isAfter(twentyFourHoursAgo)) {
          hiImAcounter++; 
          console.log(openIssues);
          $('.openIssueCount').html(openIssues);

        }
      }

    });
// hiImAcounter now has a count

remember.each is asynchronous so if you check the counter right away it might not be set -- you would have to use a promise to guarantee the loop had finished.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM