Convert array of objects in key value pairs into single object in javascript
What we have below is an edited response from a WSProxy api retrieve call to the SubscriberStatusEvent SOAP object. Within the “Results” array, we can see that the “Properties” array is an array of objects, with each object having two attributes, Name and Value.
....
var res = prox.retrieve("SubscriberStatusEvent", cols, filter);Write("Output:<br><br>" + Stringify(res));****************
Output:{
"Status": "OK",
"RequestID": "3558ebd5-4cb2-4cfb-83e6-5cc9b0f29774",
"Results": [
{
"ObjectID": "39a0d2c7-752e-e911-80d8-1402ec74dd75",
"CreatedDate": "2019-02-11T21:25:04.640",
"Properties": [
{
"Name": "SubscriberID",
"Value": "33919819"
},
{
"Name": "SubscriberKey",
"Value": "0036F00002uLTBaQAe"
},
{
"Name": "CurrentStatus",
"Value": "unsub"
},
{
"Name": "PreviousStatus",
"Value": "normal"
},
{
"Name": "ReasonUnsub",
"Value": "Unsubscribed via Import"
}
]
}],
"HasMoreRows": false
}
So, how can we convert/rearrange the Properties array:
"Properties": [
{"Name": "SubscriberID", "Value": "33919819"},
{"Name": "SubscriberKey", "Value": "0036F00002uLTBaQAe"},
{"Name": "CurrentStatus", "Value": "unsub"},
{"Name": "PreviousStatus", "Value": "normal"},
{"Name": "ReasonUnsub", "Value": "Unsubscribed via Import"}
]
to something that resembles the below format:
"Properties": {
"SubscriberID": "33919819",
"SubscriberKey": "0036F00002uLTBaQAe",
"CurrentStatus": "unsub",
"PreviousStatus": "normal",
"ReasonUnsub": "Unsubscribed via Import"
}
(A) Solution
We can run a for loop on the “Properties” array and rearrange the data.
var ourData = [{"Name": "SubscriberID", "Value": "33919819"}, {"Name": "SubscriberKey", "Value": "0036F00002uLTBaQAe"}, {"Name": "CurrentStatus", "Value": "unsub"}, {"Name": "PreviousStatus", "Value": "normal"}, {"Name": "ReasonUnsub", "Value": "Unsubscribed via Import"}]var obj = {};for (var i=0; i<ourData.length; i++) { obj[ourData[i]["Name"]] = ourData[i]["Value"];}
This will loop through each item within the “ourData” array, collecting the Name and Value pair for the object, creating the property and adding it to the obj
object.
NOTE: The syntax obj[ourData[i]["Name"]]
is how we add new dynamic properties to an object after its initial creation. Dot Notation (for example like; obj.ourData[i].Name
) will NOT work if the property we are setting is dynamically created at runtime. Use dot notation only when you know the name of the property. Thus, we need to use square bracket notation when the name of the property is dynamically determined. Recall the for loop is what is dynamically creating the property. More on this here.
function wsUnpack(ourData) {
var obj = {}; for (var i=0; i<ourData.length; i++) {
var item = ourData[i];
obj[item.Name] = item.Value;
}
return obj;
}