Getting this error when try to use forEach on an array passed to a function : TypeError: users.forEach is not a function

I create a new array, or rather an empty one, then do some processing on it then pass it on to the function, but seems the function can't use forEach on the array I passed as input to the function, I can write that part of the code directly inside my body of code, but my question is why shouldn't this work?

this is the function I passed my array to:

function checkindex(users) {
    var index;
    var bool;
    users.forEach(element => {
        if (msg.payload != element.username) {
            bool = false;
        }
        else {
            index = users.findIndex(obj => obj.username == msg.payload);
            m_index = index;
            bool = true;
        }
    });
    return bool;
}

and this is the parts of my codes body that might be needed for further analysis (note that there is global array users which is then put into my local users variable, and that global variable is an array):

var users = new Object;
users = global.get('users');
let user = { "username": msg.username, "password": msg.password, "Token": msg.token, "Submission-Time": msg.currentTime, "Expiration-Time": msg.tkExpire };
let check = checkindex(users);
if (check)
{
    users[m_index] = user;
}
else{}

Your code is passing whatever is returned by global.get('users') to your function.

The most simple explanation is that isn't returning an array.

How are you setting the value of users in global context to begin with? That isn't shown in this code.

You could add a node.warn(users) after the call to global.get so you can see exactly what you've got.

1 Like

yeah my bad, instead of creating an array inside my global users, I created a single object with multiple properties, fixed that part and the function works fine.
Although I think it would be more convenient if the function autocomplete module supported more of the JS codes. I mean like IDEs do,

but still, thanks for the help :smiley:

It does, already. However global.get returns any so you have to be explicit.

For example, if you state it IS an array (using a JSDoc hint) then you get the help...

/** @type {object[]} Array of user objects */
const myUserArray = global.get('users') || []
if(Array.isArray(myUserArray) === false) {
  node.error('Expected an array of users - check global.users', msg);
  return null;
}
msg.payload = myUserArray.length
return msg

1 Like

right, although sometimes even if I have initialized it explicitly, it would not work,
but right now I tried it again and it worked, seems in this case the same "defining an object instead of an array" was the culprit.
also most of the time I write my code elsewhere and paste in the node, so I did not realize it works for most of the data-types.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.