Loop within an array

Hello,
I'm a totally newby with node-red (and javaScript). I'm receiving an array and would like to look for an entry with two specific values. It these values match, set a variable to 1 (to grant access and open the door) and terminate the loop. I have tried with the following function node, but it complains because there is an 'Error in JavaScript code'

let access=0;
for (i = 0; i < msg.payload.length; i=i+1)
    if(msg.payload[i].clients[0].idColegiat = "3554" && payload[i].idSala = "3") {
      access = 1;
	  i = msg.payload.length;
    }
msg.payload = authorize;
return msg;

Any hint or advise would be really appreciated. Thanks!!

Hi and Welcome,

Something like?

let access = 0;
for (let i = 0; i < msg.payload.length; i++) {
    if (msg.payload[i].clients[0].idColegiat == "3554" && payload[i].idSala == "3") {
        access = 1;
        break;
    }
}
msg.payload = access;
return msg;
2 Likes

You can also use the JS built in array method find(), which searches for the first entry which meets a specified condition. For example:

const found = userArray.find(user => user.username === "alice");

if (found) {
...
}
2 Likes

Welcome to the forum @alebaca

You need to declare the variable i
for (let i=0; ...
You need to put braces round the for code block

for (let i = 0; i < msg.payload.length; i=i+1) {
    if(msg.payload[i].clients[0].idColegiat = "3554" && payload[i].idSala = "3") {
      access = 1;
	  break;
    }
}

And explicitly breaking from the loop is better form than setting a high value for i
i++ or i+=1 are a bit nicer than i = i + 1

1 Like

Also need == for testing equality.

2 Likes

Thanks! It worked (after adding a msg. in front of payload[i]idSala I had also forgotten). Thanks for all your suggestions!

Thanks! I will take a look to that function also (but, by the moment, it's too much for me; the old-style 'if' is working.

It is the first time i see this in a for loop. I didnt even think it was possible. Im so used to using i++. What i noob I am

Wait till you see i+=1 :joy:

2 Likes

Another alternative is to use array.some

msg.payload = msg.payload.some(item => item.clients[0].idColegiat === "3554" && item.idSala === "3") ? 1 : 0;
return msg
1 Like

I think it's fair to say that @alebaca managed to pack quite a few beginners' mistakes into a few lines of javascript, none of us managed to spot all of them.

Still, everyone is a beginner sometime, I hope Alejandro is not too discouraged by this experience :slightly_smiling_face:

1 Like

thanks all for your suggestions and comments!