DMS-KH
DMS-KH

Reputation: 2787

How to use loop through for an object in jquery?

the firstly I create a variable to store value from a loop after that variable get the value i want to using For() to loop through that object by using javascript function like Object and Keys but I can't see any thing in console.

<script>
 $(document).ready(function () {
        $.ajax({
            method: "GET",
            url: '<?PHP echo base_url('main/select_cat_by_group');?>',
            dataType: "Json",
            success: function (data) {
                fieldArray = {};
                $.each(data, function (i, val) {
                    fieldArray[val.gid] = val.gid;
                });
                for (var i = 0; i >= Object.keys(fieldArray).length; i++){
                        console.log(i);
                }
            }
        });
});
</script>

This is the Object result that I console.log(fieldArray);

enter image description here

Upvotes: 1

Views: 48

Answers (2)

nihar jyoti sarma
nihar jyoti sarma

Reputation: 541

The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed

for (variable in object) {...
}

variable A different property name is assigned to variable on each iteration. object Object whose enumerable properties are iterated.

Upvotes: 0

Andy
Andy

Reputation: 63524

It's better to use a for..in loop to iterate over objects:

for (var p in fieldArray) {
  console.log(p + '=>' + fieldArray[p]);
}

DEMO

Upvotes: 1

Related Questions