Last active
August 29, 2015 14:21
-
-
Save bargar/c56f4e56771ff15925d6 to your computer and use it in GitHub Desktop.
Rename key wherever found within an object
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 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