Friday, June 8, 2018

Working with messages - part 3

Here is an interesting use case. Now we want to generate the object like below:

[{"name1":1},{"name2":2},{"name3":3}]

However, the original data is no longer other object but instead a couple  of arrays, like below:

let arrName = ["name1","name2","name3"];
let arrNumber = [1,2,3];

I can imagine many different solutions, let´s use the one that seems to be the simplest.


It is just a matter of combining the pairs name and value from each array. It could be done with a while loop to iterate over the arrays, the method array.shift to extract the elements from the arrays, the method array.push to load them into a temporary array. It will be necessary to combine the pair name and value into a single object. This last part could be achieved by using the property value shorthand that goes like this:

 { name: name, value: value}  can be coded  {name, value}, no need to repeat the variable name if it is the same as the key in the object. 


Therefore the code inside the function node would be as follows:

let outputMsg = [];
let arrName = ["name1","name2","name3"];
let arrNumber = [1,2,3];

while (arrName.length > 0) {
name = arrName.shift();
value = arrNumber.shift();
outputMsg.push({ name, value });
}

msg.payload = outputMsg;
return msg;



and this is how the debug node will display the results in the side panel of Node-Red;





Node-Red flow:

[{"id":"74cfb3c0.34942c","type":"inject","z":"43f25cb3.43e2d4","name":"","topic":"","payload":"","payloadType":"date","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":303,"y":285,"wires":[["d79853f4.ef2cc"]]},{"id":"544646e7.ce3208","type":"debug","z":"43f25cb3.43e2d4","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","x":691.0000076293945,"y":285.00000381469727,"wires":[]},{"id":"d79853f4.ef2cc","type":"function","z":"43f25cb3.43e2d4","name":"Two Arrays to Object","func":"let outputMsg = [];\nlet arrName = [\"name1\",\"name2\",\"name3\"];\nlet arrNumber = [1,2,3];\n\nwhile (arrName.length > 0) {\nname =  arrName.shift(); \nvalue = arrNumber.shift();\noutputMsg.push({name, value});\n}\n\nmsg.payload = outputMsg;\nreturn msg;","outputs":1,"noerr":0,"x":499.99999809265137,"y":286,"wires":[["544646e7.ce3208"]]}]


No comments: