views:

429

answers:

2

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?

+3  A: 

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

This should work then:

obj = eval('{' + str + '}');
Philippe Leybaert
JSON requires quotations around key values, doesn't it?
cdleary
It does, but eval() will work without them.
Philippe Leybaert
Oh, right. Duh. :-)
cdleary
this is a potential security hole. I wouldn't reccomend this method at all.
Breton
It depends where the data comes from. Some people are obsessed with security. If you control your data, you can be more pragmatic in finding solutions. Or do you have a burglar-proof door between your kitchen and living room?
Philippe Leybaert
+4  A: 

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.

cdleary