Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

get index of loop in associative array using for ( key in array )

I have this associative array and use this code to loop but i need to get the index of loop for keys. I mean to get 0, 1, 2 …

    var obj={'key1': 'value1','key2':'value2'};

for (var index in obj) {
    if (!obj.hasOwnProperty(index)) {
        continue;
    }
    console.log(index);
    console.log(obj[index]);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Use Object.keys to get the properties of the object as an array, then use forEach:

const obj = {
  'key1': 'value1',
  'key2': 'value2'
};

Object.keys(obj).forEach((key, index) => {
  console.log(key, obj[key], index)
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading