dileep H dileep H - 3 months ago 12
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

"test":"one","testTwo":"two"

Answer

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;
}, {});

console.log(output);