Last active
August 29, 2015 13:57
-
-
Save tacone/9728350 to your computer and use it in GitHub Desktop.
How to interpolate/evaluate javascript object keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Will evaluate all the keys of a given object containing a plus sign "+" | |
* to the expression result. | |
* | |
* example: | |
* var a = 2; | |
* var obj = { " 'hello' + a " : true }; | |
* rewriteProperties(obj); // returns { hello2: true } | |
* | |
*/ | |
/*jshint evil:true */ | |
function rewriteProperties(obj) { | |
if (typeof obj !== "object") | |
{ | |
return obj; | |
} | |
for (var prop in obj) { | |
if (obj.hasOwnProperty(prop)) { | |
obj[prop] = rewriteProperties(obj[prop]); | |
if ( prop.indexOf("+") !== -1) | |
{ | |
// a blow straight to the face of best practices | |
var key = eval (prop); | |
obj[key] = obj[prop]; | |
delete obj[prop]; | |
} | |
} | |
} | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment