userbb
userbb

Reputation: 1874

Eval Method of object

Suppose I have an object in javascript such as:

var x = { 
    "var1":2, 
    "var2":function(){return this.var1;}
}

How to transform var x so it will be printed as:

var x = { 
    "var1":2, 
    "var2":2
}

Upvotes: 0

Views: 58

Answers (1)

TAGraves
TAGraves

Reputation: 1409

If you want to replace an object's methods with the return values of those methods, you can do so like this:

var x = { 
    var1: 2, 
    var2: function(){return this.var1;}
};


for(var prop in x) {
    if (typeof x[prop] === "function") {
        x[prop] = x[prop]();
    }
}

As others have noted, you haven't provided JSON, since functions do not have a representation in JSON. You'd have to represent the functions as strings, check if the strings looked function-y via Regexp, wrap the string in parentheses, and then eval the strings. Note also that if the method takes parameters there will be no way to specify what the values of those parameters should be, so the Regexp should only check for functions without parameters. This should do the trick:

var x = { 
    var1: 2, 
    var2: "function () { return this.var1;}"
};


for(var prop in x) {
    var val = x[prop].toString();
    val = val.replace(/ /g, "");
    if (typeof x[prop] === "function") {
        x[prop] = x[prop]();
    } else if (val.match(/^function\(\){/i)) {
        x[prop] = eval("(" + x[prop] + ")");
    x[prop] = x[prop]();
    }
}

Upvotes: 1

Related Questions