Home > Enterprise >  For Loop with Js inside WSO2 - id undefined
For Loop with Js inside WSO2 - id undefined

Time:10-24

I have a situation like this. Given an array, I do only need to iterate and extract a new json at the end called couple with id, and type, but I always have id undefined -> I really can't understand the reason, since if i try this script on a js runner online it works ( with console.log and not print )

please note elementsToUpdate is something like this :

[{
    "id": 10,
    "name": "Andrea",
    "type": "Human",
    "age": 22
 }, {
    "id": 15,
    "name": "Marco",
    "type": "Alien",
    "age": 19,
    "others": {
        "type": "ndf"
    }
 }]

And my script in wso2 is :

<script language="js"><![CDATA[var elements = mc.getProperty('elementsToUpdate');
         var payload = [];
         print('elements dentro js prima del for: '    elements);          
         for (var i in elements) { 
         print('dentro il for di js');      
         var id= elements[i].id;
         print('dentro il for di js l id  '  id );
         var type=elements[i].type; 
         var couple= {"id" : id ,"type" : type};
         payload.push(couple);   }
         print('result in JSON: ' , payload );
        var result= mc.setPayloadJSON(payload);]]></script>

Pics of the error

Thank you as always for your time, I do really appreciate it a lot.

CodePudding user response:

Your script has multiple issues. Let me try to explain a few.

var elements = mc.getProperty('elementsToUpdate');

The above line may retrieve the content from a property but may not guarantee it's always a JSON object. So to make sure you read your payload as a JSON I used the enrich mediator to persist the array as the body and used mc.getPayloadJSON() to read as a JSON object.

for (var i in elements)

Above is a for-each type loop so that you will be iterating over elements. So i will be an element of the Array, not a index that increments, hence this syntax is wrong elements[i].type

I have made slight modifications to your script. Check the below.

<enrich>
  <source clone="false" type="property" property="elementsToUpdate"/>
  <target action="replace" type="body"/>
</enrich>
<script language="js"><![CDATA[
      var elements = mc.getPayloadJSON();
      var payload = [];
      print('elements dentro js prima del for: '    elements);          
      for (var i = 0; i < elements.length; i  ) { 
        print('dentro il for di js == '  elements[i]);      
        var id = elements[i].id;
        print('dentro il for di js l id  '  id );
        var type= elements[i].type; 
        var couple= {"id" : id ,"type" : type};
      payload.push(couple);   }
      print('result in JSON: ' , payload );
      var result= mc.setPayloadJSON(payload);]]>
</script>
  • Related