Skip to content

Instantly share code, notes, and snippets.

@tacone
Last active August 29, 2015 13:57
Show Gist options
  • Save tacone/9728350 to your computer and use it in GitHub Desktop.
Save tacone/9728350 to your computer and use it in GitHub Desktop.
How to interpolate/evaluate javascript object keys
/**
* 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