[SOLVED] Msg.payload : objects to string in a sentence (need help !)

Hello you who reads me. :wink:
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 ..."

msg.classes = {john:3,paul:1,juliette:2}
return msg

I think there are object to array conversions. And that's where everything gets muddled. :crazy_face:
Any help is appreciable

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.*)


the answer will be in msg.total

Hi @SuperNinja

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;

I note it anyway, thanks

pretty! thank you !
Now I have time to understand how it works :+1:

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