jeremy
jeremy

Reputation: 185

Trying to use forEach

I'm trying to use the forEach method but I'm getting an error saying that forEach is not a function.

let users = []
// Retrieve all users
router.get('/api/users', (req, res) => {
  dbConn.query('SELECT * FROM users', function (error, results, fields) {
    if (error) throw error;
    //console.log(res.json(results))
    res.forEach(result => {
      users.push(result)
    })
  });
});

Upvotes: 0

Views: 88

Answers (3)

turbopixel
turbopixel

Reputation: 142

The forEach() can be applied directly to an array.

If you have an object, you have to call forEach() with Object.keys(myObject):

var obj = {foo: 'hello', bar: 'my', too: 'world'};

Object.keys(obj).forEach(function(item){
    console.log(item);
});

Output key name:

bla
too
foo

To get the value:

var obj = {foo: 'hello', bar: 'my', too: 'world'};

Object.keys(obj).forEach(function(item){
    console.log(obj[item]);
});

Output value:

hello
my
world

Upvotes: 0

Naveen Kumar V
Naveen Kumar V

Reputation: 2809

SOLUTION:

Whatever the object you are trying to iterate.

First check if the object is of Array type since forEach supports only the Array.

if (anyObj instanceof Array) {
  // Do your work
}

Working example:

var a = { 'a': 1 };
var b = [{ 'a': 1 }];

// This fails
if (a instanceof Array) {
  console.log("Iterating a");
  a.forEach (x => console.log(x));
}

// This gets executed
if (b instanceof Array) {
  console.log("Iterating b");
  b.forEach (x => console.log(x));
}

Upvotes: 0

Danilo Jakob
Danilo Jakob

Reputation: 81

I guess you're making the forEach statement over the wrong object?
Maybe you should try to use results.forEach instead of res.forEach.

Upvotes: 1

Related Questions