Soufiaane
Soufiaane

Reputation: 2087

Convert string to object in NodeJS

I have a string in this format:

var x = "a=1; b=2; c=3; d=4"

and I would like to convert it to an object like this:

var y = {
    a: "1",
    b: "2",
    c: "3",
    d: "4"
    }

Any ideas how to achieve that?

Upvotes: 1

Views: 7252

Answers (3)

jacoborus
jacoborus

Reputation: 76

This works in iE9+

var x = "a=1; b=2; c=3; d=4",
    y = {};

x.split(';').map(function (i) {
  return i.split('=')
}).forEach(function (j) {
  y[j[0].trim()] = j[1]
});

If you are using Node.js v4+

let x = "a=1; b=2; c=3; d=4",
    y = {}

x.split(';').map(i => i.split('=')).forEach(j => y[j[0].trim()] = j[1])

Upvotes: 5

Soufiaane
Soufiaane

Reputation: 2087

here is what i did and it seems to work fine:

var y = x.split(";");
var obj = {};
for(var i = 0; i < y.length ; i++){
    var k = y[i].split("=");
    var r = k[0].replace(" ", "");
    obj[r] = k[1];
}
console.log(obj);

Upvotes: -1

user1636522
user1636522

Reputation:

You could try this (not bullet proof, refer to comments):

var json, str;
str = 'a=1; b=2; c=3; d=4';
str = str.replace(/\s*;\s*/g, ',');
str = str.replace(/([^,]+)=([^,]+)/g, '"$1":"$2"');
str = '{' + str + '}';
json = JSON.parse(str);

document.write(
  '<pre>' + JSON.stringify(json) + '</pre>'
);

Upvotes: 0

Related Questions