Created
October 3, 2012 09:27
-
-
Save LaleWolf/3826032 to your computer and use it in GitHub Desktop.
Change property names of a collection [Underscore.js mixin]
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
_.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]]; | |
} | |
}); | |
}); | |
} | |
}); |
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
var collection = [ | |
{ | |
"prop1" : "val", | |
"prop2" : "val" | |
}, | |
{ | |
"prop1" : "val", | |
"prop2" : "val", | |
"prop3" : "val" | |
}, | |
{ | |
"prop2" : "val" | |
} | |
]; | |
var translation = { | |
"prop1" : "property1", | |
"prop2" : "property_two" | |
}; | |
_.renameProperties(collection, translation); |
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
_.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