BeeNag BeeNag - 1 year ago 72
Javascript Question

Converting an array of strings into an array of objects

I have an array of strings:

["14: London", "15: Manchester", "16: Bristol"]

I need to change it into an array of objects that would look like this:

[{14: "London"}, {15: "Manchester"}, {16: "Bristol"}]

I assume that the best way to go about this is to first iterate over the array and split each string and then convert it into an object before pushing back into an array.

I can't really figure out how to make it work though, so any help would be much appreciated.

Thanks for your time

Answer Source

Use Array#map method to generate the array.

var arr = ["14: London", "15: Manchester", "16: Bristol"];

// iterate over the array
var res = {
  // split the value based on `:`
  var splitArr = v.split(':'),
    // initialize an object  
    obj = {};
  //define the property value
  obj[splitArr[0].trim()] = splitArr[1].trim();
  // return the generated object
  return obj;


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download