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]);
}
Advertisement
Answer
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)
})