String to object in JS

String to object in JS

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?


Solution 1:

Actually, the best solution is using JSON:


JSON.parse(text[, reviver]);



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


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

Passing a function to JSON

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

Solution 2:

Your string looks like a JSON string without the curly braces.

This should work then:

obj = eval('({' + str + '})');

Solution 3:

If I’m understanding correctly:

var properties = string.split(', ');
var obj = {};
properties.forEach(function(property) {
    var tup = property.split(':');
    obj[tup[0]] = tup[1];

I’m assuming that the property name is to the left of the colon and the string value that it takes on is to the right.

Note that Array.forEach is JavaScript 1.6 — you may want to use a toolkit for maximum compatibility.

Related:  Popup window to return data to parent on close

Solution 4:

This simple way…

var string = "{firstName:'name1', lastName:'last1'}";
eval('var obj='+string);



Solution 5:

if you’re using JQuery:

var obj = jQuery.parseJSON('{"path":"/img/filename.jpg"}');
console.log(obj.path); // will print /img/filename.jpg

REMEMBER: eval is evil! 😀

Solution 6:

You need use JSON.parse() for convert String into a Object:

var obj = JSON.parse('{ "firstName":"name1", "lastName": "last1" }');