adnanerlansyah403's avatar

How to check object length with jquery in loop each function

Hello everyone, i have a problem about foreach data. which is of type object, so I want to foreach data by using the $.each function of jquery. and checks if the value of the object is more than 4 or equal to 4. then the action stops or returns false.

I've tried checking it with the length function but it doesn't work. and when I check the index, the value is not increment. but it gets random value.

So for example, this is my code

carts = data.carts;
let miniCart = ""
// Foreach the object data
          $.each( carts, function(index, value) {


            miniCart +=  `

                <div class="cart-item product-summary">
                  <div class="row">
                    <div class="col-xs-4">
                      <div class="image"> <a href="detail.html"><img src="/${value.options.image}" alt=""></a> </div>
                    </div>
                    <div class="col-xs-7">
                      <h3 class="name"><a href="index.php?page-detail">${value.name}</a></h3>
                      <div class="price">$ ${value.price} * ${value.qty}</div>
                    </div>
                    <div class="col-xs-1 action"> 
                      <button type="submit" class="btn btn-danger" id="${value.rowId}" onclick="miniCartRemove(this.id)"><i class="fa fa-trash"></i></button> 
                    </div>
                  </div>
                </div>
                <!-- /.cart-item -->
                <div class="clearfix"></div>
                <hr>

            `;
                    

            // Check Length of Index / Value
            
          });
$('#miniCart').html(miniCart);

0 likes
2 replies
sr57's avatar

the value of the object is more than 4

what the value of an object?

To check the index and return false, you should do

if ( index >= 4) return false

$ ${value.price} * ${value.qty}

should be

$[value.price * value.qty}

adnanerlansyah403's avatar
Level 1

Thank you guys, but I'm already fix it with array. So I put the value in array again when in looping and I checked it the length of array.

Please or to participate in this conversation.