-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
};
4
  • If it's not coming from user input, just use eval. Commented Nov 21, 2015 at 16:09
  • You can use a regex to parse the string /(.+?): (.+?),?/g Commented Nov 21, 2015 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. Commented Nov 21, 2015 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. Commented Nov 21, 2015 at 17:12

1 Answer 1

-2

You could use the eval function as follows:

eval("var obj = {" + yourString + "}"); 
console.log(obj);
Sign up to request clarification or add additional context in comments.

1 Comment

FWIW, This answered my question and parse did not work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.