skip to Main Content
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


  1. 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)
    
    Login or Signup to reply.
  2. You could convert the object with index like keys to an array and use it.

    const
        object = { 0: 'Jo', 1: 'Ali', 2: 'Jane' },
        array = Object.assign([], object);
        
    array.forEach(v => console.log(v));
    Login or Signup to reply.
  3. How about a simple for..in loop. This literally what it’s made for.

    var obj = {
      0: 'Asad',
      1: 'Ali',
      2: 'Rizwan'
    }
    console.log(obj);
    
    for (const key in obj) {
      console.log('item', key, obj[key]);
    }
    Login or Signup to reply.
  4. 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 a length property2.

    The following object has indexes but not a length property:

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

    Once length is added Array#forEach can be used against it using Function#call():

    var obj = {
        0: 'Asad',
        1: 'Ali',
        2: 'Rizwan',
        length: 3
    }
    
    let FOREAC = Array.prototype.forEach;
    
    FOREAC.call(obj, (item) => {
        console.log('ITEM LOGS');
        console.log(item);
    
        return true;
    });
    .as-console-wrapper { max-height: 100% !important; }

    Or Function#apply():

    var obj = {
        0: 'Asad',
        1: 'Ali',
        2: 'Rizwan',
        length: 3
    }
    
    let FOREAC = Array.prototype.forEach;
    
    FOREAC.apply(obj, [(item) => {
        console.log('ITEM LOGS');
        console.log(item);
    
        return true;
    }]);
    .as-console-wrapper { max-height: 100% !important; }

    1 non-negative integers
    2 also a non-negative integer. It should show the next available index.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search