Skip to content

Instantly share code, notes, and snippets.

@LaleWolf
Created October 3, 2012 09:27
Show Gist options
  • Save LaleWolf/3826032 to your computer and use it in GitHub Desktop.
Save LaleWolf/3826032 to your computer and use it in GitHub Desktop.
Change property names of a collection [Underscore.js mixin]
_.mixin({
renameProperties: function (object, translations) {
_.each(_.pairs(translations), function(translation) {
_.each(object, function(item){
if (item.hasOwnProperty(translation[0])) {
item[translation[1]] = item[translation[0]];
delete item[translation[0]];
}
});
});
}
});
var collection = [
{
"prop1" : "val",
"prop2" : "val"
},
{
"prop1" : "val",
"prop2" : "val",
"prop3" : "val"
},
{
"prop2" : "val"
}
];
var translation = {
"prop1" : "property1",
"prop2" : "property_two"
};
_.renameProperties(collection, translation);
_.mixin({
renameProperties: function (object, translations) {
_.each(_.pairs(translations), function(translation) {
_.each(object, function(item){
if (item.hasOwnProperty(translation[0])) {
item[translation[1]] = item[translation[0]];
delete item[translation[0]];
}
return item;
});
});
return object;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment