2

Given the following object:

var obj = { a: 1 };

and the following string:

var s = "b: 2";

what I need is to end with the following object, after evaluating the string s:

obj === { a:1, b:2 }

I tried with eval but couldn't figure it out. any ideas?

ps0604
  • 1,513
  • 20
  • 113
  • 274

4 Answers4

1

Eval can be harmful so instead try something like this

var obj = { a: 1 };
var s = "b: 2";
s = s.replace(/\s/g, '').split(":");
obj[s[0]] = s[1];

var obj = { a: 1 };
var s = "b: 2";
s = s.replace(/\s/g, '').split(":");
obj[s[0]] = s[1];
alert(JSON.stringify(obj));
Community
  • 1
  • 1
Dhiraj
  • 32,144
  • 8
  • 59
  • 77
0

You can dynamically set object properties by using this notation obj[propName] = value. In your case I used substring to cut up your value and property name.

obj[s.substring(0,1)] = s.substring(3,4);
floor
  • 1,489
  • 10
  • 24
0

This will also work for multiple key value pair in string.

 var obj = {a: 1};
    str = "b: 2";
    var strArr = str.split(',');
    for (var index in strArr) {
        var strMap = strArr[index].split(':');
        obj[strMap[0].trim()] = parseInt(strMap[1].trim());
    }

Here, Simply I split the string into array and then traverse through it and generate required map.

TechnoCrat
  • 711
  • 10
  • 20
0

eval() treats string as normal code so you can just return desired value by using return keyword.

    var expression = "{b:2}";
    var expString = "return " + expression + ";"

    // returns Object{ b : 2 }
    alert(eval("(function() {" + expString + "}())").b); 

Note:

  1. eval() is considered as a high risk function, it can be use to exploit your solution.
  2. Have you heard of JSON data model ? check it here .
Piotr Dajlido
  • 1,945
  • 14
  • 27