soum soum - 2 years ago 105
jQuery Question

converting string array into a key value pair object

I am getting an output which looks like this

var x = ["title: x_one", " description: 1", " value: 4"]

title: x_one

Which is a string. I cant read the property of title. How would I convert it into an object so that eventually I will be able to loop through the array and read the properties such as title, description and value.

I am trying to do this through jquery

I have been looking for a solution but havent really found one. If there is any out there which I am missing I would highly appreciate if anyone else have and could point me to that

Answer Source

Loop through your array, splitting the values at the : character. Then use the first part as a property name, the second part as the value, in an object.

var obj = {};
for (var i = 0; i < x.length; i++) {
    var split = x[i].split(':');
    obj[split[0].trim()] = split[1].trim();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download