Brian Var
Brian Var

Reputation: 6227

How to map new property values to an array of JSON objects?

I'm reading back record sets in an express server using the node mssql package. Reading back the values outputs an array of Json objects as expected.

Now I need to modify the Email propoerty value of each Json object. So I tried looping through the recordset and changing the value at each index:

            var request = new sql.Request(sql.globalConnection);
            request.input('p_email', sql.VarChar(50), userEmail);
            request.execute('GetDDMUserProfile', function(err, recordsets, returnValue) {      

               for (var i = 0; i < recordsets.length; i++){
                    recordsets[i].Email = "[email protected]";

                }

                console.log(recordsets);

            });

But instead of modifying the Emailvalue of each Json object, this code just appends a new email property to the last Json object.

How can you map new property values to an array of JSON objects?

Example output: An example of the output is shown below, where a new Email property has been added to the end of the array instead of changing each existing property value:

[  
   [  
      {  
         ID:[  
            4
         ],
         UserName:"Brian",
         Email:"[email protected]"
      },
      {  
         ID:[  
            5
         ],
         UserName:"Brian",
         Email:"[email protected]"
      }      
   Email:'[email protected]' ]
]

Upvotes: 1

Views: 54

Answers (1)

jeffdill2
jeffdill2

Reputation: 4114

The issue here is that your dataset appears to not be an array of JSON objects but, rather, an array of arrays of JSON objects. If you know for certain that you'll always have only one array in the top-most array, then you can solve the problem like this:

recordsets[0][i].Email = "[email protected]";

to always target the first array in the top-most array. However, if the top-most array could potentially have more than one array, that'll be a different kind of issue to solve.

Upvotes: 1

Related Questions