dileep H dileep H - 1 month ago 4x
Javascript Question

How to Convert key/value pair String to a JSON object?

How can I covert key=value pair string to json object

input :

test = one
testTwo = two

Output should be json object



Is input a string? You could first split it by \n to get an array of key/value-pairs, and then split each pair by =, to get an array of the key and the value.

var input = `test = one
testTwo = two
testThree = three
testFour = four`;

var output = input.split('\n').reduce(function(o,pair) {
   pair = pair.split(' = ');
   return o[pair[0]] = pair[1], o;
}, {});