I have a case where I need to parse a string into JS object by binding this like below:
var jsString = '{"name" : this.name, "age": this.age}';
this.name = "Hello";
this.age = 100;
//This fails(CASE 1)
var jsObjectFromString = JSON.parse(jsString);
console.log(jsObjectFromString );
//This works(CASE 2)
var directObject = {"name" : this.name, "age": this.age};
console.log(directObject);
//Need below output for console.log(jsObjectFromString ):
//{"name" : "Hello", "age": 100}
In my actual program, the string is coming from a web-service & hence I can't use CASE 2 approach.
I can traverse the JS object & set params after parsing like below:
var jsonString = '{"name" : "", "age": 0}';
var jsonObject = JSON.parse(jsonString);
jsonObject["name"] = this.name;
jsonObject["age"] = this.age;
But there a lot of inner objects & traversing would be a kill. I tried the below but failed(obviously :( ):
JSON.parse(jsonString).bind(this);
Is there an approach to overcome this?
PS: This is a browser based app not a node project.
Edit: I want to construct a javascript object from the string. I would want to replace parts of the string(like name,age) into actual values in the parsed Javascript object.