1

I have this Json object which i'm trying to loop through a jquery each function. inside of it I have an if condition to specify some values.

My JSON object is here

{
  "times": [
    {
      "visit_time": "01.30pm-01.45pm",
      "count": "3"
    },
    {
      "visit_time": "02.15pm-02.30pm",
      "count": "1"
    },
    {
      "visit_time": "02.30pm-02.45pm",
      "count": "3"
    }
  ],
  "slots": "20"
}

My code is here. 'data' catches the JSON object

function (data) {
          console.log(data);
          $.each(data.times, function(key, value) {
            console.log(value.count);
            if(value.count <= data.slots){
              console.log(data.slots);
            }

          });
        }

The console.log() as this

3 , 1 , 20 , 3

As for my understanding it should be 3 , 20 , 1 , 20 , 3 , 20

This is what i'm expecting to get from the code also. Please someone explain me why i'm wrong or what's wrong with my code is.

ashen25
  • 29
  • 7

1 Answers1

2

You need to convert your strings to numbers if you want to compare them like that. If you can't change them in the json, you'll need to convert them.

You could do something as simple as adding + directly in front of the string to convert it. There are multiple ways to convert strings to numbers, so pick the method that suits your needs.

const stuff = {
  "times": [{
      "visit_time": "01.30pm-01.45pm",
      "count": "3"
    },
    {
      "visit_time": "02.15pm-02.30pm",
      "count": "1"
    },
    {
      "visit_time": "02.30pm-02.45pm",
      "count": "3"
    }
  ],
  "slots": "20"
}

function t(data) {
  console.log(data);
  $.each(data.times, function(key, value) {
    console.log(value.count);
    if (+value.count <= +data.slots) {
      console.log(data.slots);
    }

  });
}


t(stuff);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
mwilson
  • 12,295
  • 7
  • 55
  • 95