Viet Le Viet Le - 1 year ago 124
Javascript Question

Small iteration in javascript

Hey guys I have a slight problem.

Can somebody show me how I would be able to separate this string into a json formatted data?


To look like this

one: apple,
two: orange,
three: bananna,
four: pears

Answer Source

Use Array#forEach over String#split

var str = "one:apple;two:orange;three:bananna;four:pears";
var obj = {};
str.split(';').forEach(function(el) {
  var x = el.split(':');
  obj[x[0]] = x[1];

Or using Array#reduce

var str = "one:apple;two:orange;three:bananna;four:pears";
var obj = str.split(';').reduce(function(a, b) {
  var x = b.split(':');
  a[x[0]] = x[1];
  return a;
}, {});

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