Convert array of objects in key value pairs into single object in javascript

Photo by Caspar Camille Rubin on Unsplash

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.

So, how can we convert/rearrange the Properties array:

to something that resembles the below format:

(A) Solution

We can run a for loop on the “Properties” array and rearrange the data.

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 objobject.

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.

I am a certified Salesforce Marketing Cloud Consultant at Bower House Digital in Melbourne, Australia.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store