BeeNag BeeNag - 8 months ago 37
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


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;