Loop array values as msg path parts

Novice here and going crazy. I'm trying to loop through the array values below to pull object elements out of the message and use them for additional calculations. I've tried every syntax I can think of and this is the closest I've come. However, I am getting the error shown in the debug snippet below on the first value. You can also see in the snippet that the ...atrisk value is in the message. Any assistance here is greatly appreciated.

Function node script...

var myArray = ["SPAQ", "NKLA", "SHLL", "ARLO", "TSLA", "FTNT", "DXCM", "DNOW"];

function netnow(i){
var atrisk = msg.holding.myArray[i].atrisk;
atrisk = atrisk.slice(1);
atrisk = atrisk.replace(/,/g,'');
atrisk = Number(atrisk);
//more calculations will go here
msg.holding.myArray[i].sellnow = atrisk;
}

var i;
for (i = 0; i < myArray.length; i++){
netnow(myArray[i]);
}

return msg;

Debug output = "TypeError: Cannot read property 'SPAQ' of undefined"

Hi and welcome to the forum!

Please format code snippets properly using the </> icon on the editor. It works best if you first click it and then paste the code in the marked area between the backtick lines.

I can see at least two bugs in your code. Line:

var atrisk = msg.holding.myArray[i].atrisk;

... should be:

var atrisk = msg.holding[i].atrisk;

And similarly line:

msg.holding.myArray[i].sellnow = atrisk;

... should be:

msg.holding[i].sellnow = atrisk;

Edit:

This line looks useless also as the value does not contain commas.

atrisk = atrisk.replace(/,/g,'');

I can't thank you enough!!!
That is a syntax I frankly don't think I ever would have tried. :grinning:

I believe you could also simplify your code a bit:

Object.keys(msg.holding).forEach(key => {
  let atrisk = msg.holding[key].atrisk;
  atrisk = atrisk.slice(1);
  atrisk = Number(atrisk);
  // more calculations will go here
  msg.holding[key].sellnow = atrisk;
});

return msg;

I'm assuming here you want to process all the objects under msg.holding. I can't see from your screenshot if there's more stock symbols there and you want to specifically handle only the listed ones.

syntax error, you forgot to close the foreach(

1 Like

Oops and thanks! Fixed.

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