var obj = {
0: 'Asad',
1: 'Ali',
2: 'Rizwan'
}
console.log(obj);
let FOREAC = Array.prototype.forEach;
FOREAC.apply(obj , ((item) => {
console.log('ITEM LOGS');
console.log(item);
return true;
}))
Above is the code I am using to iterate my object obj
. It does not show any output.
Thanks In Advance
I am trying to iterate my object obj
. But my code does not shows any output
4
Answers
You can use Object.entries to iterate over all pairs in an object.
Edit: However as your object does not contain any information in the key position (only indexes) you could also use Object.values to generate an Array from the object values:
You could convert the object with index like keys to an array and use it.
How about a simple
for..in
loop. This literally what it’s made for.Array methods like
Array#forEach()
are intentionally generic to work with not only arrays but any array-like object. In short, an array-like has indexes as keys1 and alength
property2.The following object has indexes but not a
length
property:Once
length
is addedArray#forEach
can be used against it usingFunction#call()
:Or
Function#apply()
:1 non-negative integers
2 also a non-negative integer. It should show the next available index.