Brian J Brian J - 29 days ago 4
JSON Question

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 = "joe@gmail.com";

}

console.log(recordsets);

});


But instead of modifying the
Email
value 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:"joe@gmail.com"
},
{
ID:[
5
],
UserName:"Brian",
Email:"joe@gmail.com"
}
Email:'joe@gmail.com' ]
]

Answer

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 = "joe@gmail.com";

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.