Search code examples
node-red

Node red how to take the attribute in array json


I need to get the age of the people to do some validation, how can i access to the field age in the json in node red?

 {
        "People": [
            {
                "NAME":"HK",
                "Age":"16"
            },
            {
               "NAME":"CK",
                "Age":"16" 
            },{
                "NAME":"DK",
                "Age":"16"
            }
        ]

    }

Solution

  • The following code in a Function node will take the given input and output a message for each element in the People array

    var array = [];
    for (var i=0; i<msg.payload.People.length;i++) {
      array.push({payload: msg.payload.People[i]});
    }
    
    return array;
    

    You can then access the age in each of those messages in the following nodes as msg.payload.age

    If you just want to check the whole array in the fist function node then something like:

    for (var i=0; i<msg.payload.People.length;i++) {
      if (msg.payload.People[i].age < 16) {
          //do something here
      }
    }