-1

If I am given properties as a string in multiple test cases...

var testCase = "Key1: 1, Key2: 2, key3: 3, key4: 4"

...is there a way in JavaScript to convert it to an object?

var myObj = {
    key1: 1,
    key2: 2,
    key3: 3,
    key4: 4
};
Daniel Breen
  • 179
  • 1
  • 2
  • 11
  • If it's not coming from user input, just use eval. – Shashank Nov 21 '15 at 16:09
  • You can use a regex to parse the string `/(.+?): (.+?),?/g` – Tivie Nov 21 '15 at 16:15
  • Yes, it's a duplicate, but the accepted answer to that duplicate does not really apply, since it assumes that the keys are quotes. –  Nov 21 '15 at 16:19
  • @torazaburo: There is no accepted answer to that question but even if there was, the accepted answer isn't an "official" answer. –  Nov 21 '15 at 17:12

1 Answers1

-2

You could use the eval function as follows:

eval("var obj = {" + yourString + "}"); 
console.log(obj);
trincot
  • 317,000
  • 35
  • 244
  • 286