0
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

Rahul T.O
  • 21
  • 7

4 Answers4

1

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));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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]);
}
Thomas
  • 11,958
  • 1
  • 14
  • 23
1

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.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
0

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)
Egge
  • 256
  • 2
  • 7