Skip to content

Instantly share code, notes, and snippets.

@bargar
Last active August 29, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bargar/c56f4e56771ff15925d6 to your computer and use it in GitHub Desktop.
Save bargar/c56f4e56771ff15925d6 to your computer and use it in GitHub Desktop.
Rename key wherever found within an object
var recursiveReplaceKey = function(object, oldKey, newKey) {
for (var key in object) {
if (object.hasOwnProperty(key)) {
if ($.isPlainObject(object[key])) {
// recurse to sub-object
util.recursiveReplaceKey(object[key], oldKey, newKey);
}
if (key === oldKey) {
object[newKey] = object[oldKey];
delete object[oldKey];
}
}
}
};
/*
var object = {
titles: {
yorkie: {
1: 'lonely',
other: 'party'
}
}
};
objectUtil.recursiveReplaceKey(object, '1', 'singular');
assert.expect(2);
assert.equal(object.titles.yorkie.singular, 'lonely');
assert.equal(object.titles.yorkie['1'], undefined);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment