-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?

2
  • 2
    doesn't seem to be always 0. Is this the actual code that gives the error? Commented Feb 22, 2022 at 18:43
  • @adam78, please check answer below, if that helps ! Commented Feb 25, 2022 at 7:49

1 Answer 1

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]);
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.