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

Javascript call method is not working on Array forEach

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

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

>Solution :

You can use Object.entries to iterate over all pairs in an object.

var obj = {
   0: 'Asad',
   1: 'Ali',
   2: 'Rizwan'
}

for (const [key, value] of Object.entries(obj)) {
   console.log(`${key}: ${value}`);
}

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:

var obj = {
   0: 'Asad',
   1: 'Ali',
   2: 'Rizwan'
}

console.log(Object.values(obj)
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