String to object in JS

hijibiji picture hijibiji · Jul 6, 2009 · Viewed 473.4k times · Source

I have a string as

string = "firstName:name1, lastName:last1"; 

now I need one object obj such that

obj = {firstName:name1, lastName:last1}

How can I do this in JS?

Answer

Matej picture Matej · Jul 11, 2013

Actually, the best solution is using JSON:

Documentation

JSON.parse(text[, reviver]);

Examples:

1)

var myobj = JSON.parse('{ "hello":"world" }');
alert(myobj.hello); // 'world'

2)

var myobj = JSON.parse(JSON.stringify({
    hello: "world"
});
alert(myobj.hello); // 'world'

3) Passing a function to JSON

var obj = {
    hello: "World",
    sayHello: (function() {
        console.log("I say Hello!");
    }).toString()
};
var myobj = JSON.parse(JSON.stringify(obj));
myobj.sayHello = new Function("return ("+myobj.sayHello+")")();
myobj.sayHello();