Reputation: 1788
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
}
Upvotes: 0
Views: 54
Reputation: 36599
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
The comma operator
evaluates each of its operands (from left to right) and returns the value of the last operand.
var str = "one:apple;two:orange;three:bananna;four:pears";
var obj = str.split(';').reduce(function(a, b) {
var x = b.split(':');
return a[x[0]] = x[1], a;
}, {});
console.log(obj);
Upvotes: 6
Reputation: 11496
var str = "one:apple;two:orange;three:bananna;four:pears";
var arr = str.split(';'), obj = {}, i = 0;
for(; i < arr.length; i++){
var x = arr[i].split(':');
obj[x[0]] = x[1]
};
console.log(obj);
x = null;
// thanks to @Rayon for edit
Upvotes: 1
Reputation: 19113
You can use regex to do this.
var str = "one:apple;two:orange;three:bananna;four:pears"
var obj = '{"'+ str.replace(/;/g, ',').replace(/[:+,]/g, '"$&"') + '"}'
console.log(JSON.parse(obj))
Upvotes: 0