-1

I have an array as follows:

result = [];
    result.push({label: 'test label 1', value: 'test value 1'});
    result.push({label: 'test label 2', value: 'test value 2'});

    $.each(result, function( key, value ) {
        console.log(key);
        console.log(value.label);
    })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

I'm trying to retrieve the index value of the item in the array using 'console.log(key)' but it always returns 0. How do i get the index value of each item in array as it iterates?

depperm
  • 10,606
  • 4
  • 43
  • 67
adam78
  • 9,668
  • 24
  • 96
  • 207

1 Answers1

0

If you want to return value of each element then you need to write as below, because key will return always current index of element.

result = [];
result.push({label: 'test label 1', value: 'test value 1'});
result.push({label: 'test label 2', value: 'test value 2'});

$.each(result, function( key, value ) {
    console.log(key);
    console.log(value.label);
    console.log(result[key]);
})