Viet Le Viet Le - 1 month ago 10
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?

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


To look like this

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

Answer

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];
});
console.log(obj);

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;
}, {});
console.log(obj);

Comments