Hello you who reads me.
It's been a year since I started on Node-red, I'm learning little by little, and doing great things. But there are still points that draw my hair, it is the manipulation of objects, tables etc.
Here is an example: a study counts the number of first names in a school class (we do not know the total number of students):
I would like to return an msg. as a String: "There are 3 johns, 1 paul, 2 juliette etc ..."
UPDARE: Oops, I should hav read it better - I thought you wanted the total students.
I love jsonata - add a change node using this jsonata expression $sum(classes.*)
[{"id":"dab3ac00.d82d","type":"change","z":"10b72cef.116283","name":"","rules":[{"t":"set","p":"total","pt":"msg","to":"$sum(classes.*)","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":210,"y":260,"wires":[["11a5247e.32987c"]]}]```
the answer will be in msg.total
you caught me at a good time... here's a Function node that will generate the sentence you want. I've even handled pluralisation of the names for you because its a Monday morning and I've got plenty of real work I should be doing.
// Get the array of names
var names = Object.keys(msg.classes);
var firstCount;
// For each name, map it to "n name"
var parts = names.map((n,i) => {
var count = msg.classes[n];
if (i === 0) {
//Remember the first count to get the "is/are" right later
firstCount = count;
}
// Return "n name" and get the pluralisation right
return count+" "+n+(count>1?"s":"")
})
// If there is more than one name, pop off the last one for later
var lastName;
if (parts.length > 1) {
lastName = parts.pop();
}
// Build up the response getting "is/are" right for the first count and joining
// the array of names with a comma
msg.payload = "There "+(firstCount === 1 ? "is":"are")+" "+parts.join(", ")
// If there was a last name, add that on the end with an 'and', not a comma
if (lastName) {
msg.payload += " and "+lastName;
}
return msg;