Hi, so, few things...
-
You have created a function that you save in global
... but this will never work as you do not pass the msg
in.
-
You dont pass the msg through to the global function
Assuming this is academic or you REALLY do want to do this, then you need to pass the base object (in this case, the msg object) into the function as a parameter...
global.set('delete_not_needed', function(msg) {
delete msg.payload.ext;
return 0;
}, 'memoryOnly');
however - this is a very limited and very specific function that has "side effects" / not "pure". I would not recommend this approach. A slightly improved version is included in the code below called deleteObjectProperty
. This is considered a better approach as it has more re-use value. (however, deletion of a property is so simple it makes no sense to have a helper function at all!)
A better solution
A slightly better way of dealing with this - put all your helper functions into 1 object for easier access. In the below code example, I make an {object} named myFunctions
and store the function
definitions in that object, THEN store the single object in global...
const myFunctions = {};
myFunctions.decimalToHex = function(d, padding) {
var hex = Number(d).toString(16);
padding = typeof (padding) === "undefined" || padding === null ? padding = 2 : padding;
while (hex.length < padding) {
hex = "0" + hex;
}
return hex;
}
myFunctions.delete_not_needed = function (msg) {
delete msg.payload.ext;
return 0;
}
/**
* @example myFunctions.deleteObjectProperty(msg.payload, "ext")
*/
myFunctions.deleteObjectProperty = function (/** @type {object}*/obj, /** @type {string}*/ propName) {
if (obj.hasOwnProperty(propName)) {
delete obj[propName];
}
}
//Store 'myFunctions' in global for later use
global.set("myFunctions", myFunctions, 'memoryOnly');
Usage
Now you have all helper functions in one object, you simply can do this...
//////////// Example usage ////////////
var myFunctions = global.get("myFunctions","memoryOnly"); //get the helper functions
//call decimalToHex from myFunctions
var hex1 = myFunctions.decimalToHex(2, 2);// ==> "02"
var hex2 = myFunctions.decimalToHex(5, 2);// ==> "05"
//call deleteObjectProperty from myFunctions
myFunctions.deleteObjectProperty(msg.payload, "ext"); //delete msg.payload.ext property from msg.payload
myFunctions.deleteObjectProperty(msg, "_meta"); //delete msg._meta property from msg
*/
example....
Lastly...
I am assuming you only want 1 property in your final msg.payload
- it is far easier to just create a new object and add the property you do want. I demonstrated that in the above screen shot, but for completeness - here is a little how to...
msg.payload = {}; //set payload to a new empty object
msg.payload.OTMR_DIGITAL_STATES = k; //add a property to msg.payload called OTMR_DIGITAL_STATES
An alternative way is...
//set payload to a new empty with 1 property
msg.payload = {
OTMR_DIGITAL_STATES : k
};
msg.payload.; //add a property called OTMR_DIGITAL_STATES