1

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

2
  • 1
    Your explanation is very good, so what did you try already? Commented Aug 16, 2016 at 15:31
  • 1
    With ES6 syntax: arr.map(function (s) { var str = s.split(':'); return { [str[0]]: str[1].trim() }; }); Commented Aug 16, 2016 at 15:33

4 Answers 4

4

Use Array#map method to generate the array.

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

// iterate over the array
var res = arr.map(function(v) {
  // 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;
})

console.log(res);

Sign up to request clarification or add additional context in comments.

1 Comment

One thing missing: Key should be Number.
2

You can map it

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

var obj = arr.map(d => {
    var split = d.split(": ");
  return {
    [split[0]] : split[1]
  }
});

Comments

1

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

var makeObjectFromArray = function(arr) {

  if (Object.prototype.toString.call(arr) !== '[object Array]') return arr;

  var objects = [];

  for (var i = 0, length = arr.length; i < length; i++) {

    var obj = arr[i].split(":");
    var temp = {};

    var key = (typeof obj[1] === 'string') ? obj[0].trim() : obj[0];
    var value = (typeof obj[1] === 'string') ? obj[1].trim() : obj[1];

    temp[key] = value;
    objects.push(temp);
  }
  return objects;
};

console.log(makeObjectFromArray(arr))

Comments

1

You could also do like this so you can know when your object already has a key/value pair with the same key:

    var testArray = ["14: London", "14: London", "15: Manchester", "16: Bristol"];
    var testObj = {};
    var length = testArray.length;
    for ( var i = 0; i < length; i++ ) {
        var newTestArray = testArray[i].split(":");
        if ( testObj[newTestArray[0]] === undefined ) {
            testObj[newTestArray[0]] = newTestArray[1];
        } else {
            console.log("key: " + newTestArray[0] + " already exists!");
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.