An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
Manipulating Keys in an Object Using Recursion
It is no secret that javascript was designed for object-oriented programming. Objects have the ability to to store string, numeric and boolean values as well as functions (methods) in an easy to read and interpret way. Because understanding objects and how they work and can be accessed is a necessity in javascript, I would like to show a an example of how you can manipulate and objects key to your will with the power of recursion!
Recursively Replacing a Key in an Object
In the event that you may need to replace a key in an object, you can use a short little function that cleverly uses recursion to replace the key in an object.
var replaceKeysInObj = (obj, key, newKey) => { let newObj = {}; for (var ogKey in obj){ if(ogKey === key) { newObj[newKey] = obj[ogKey] } else if (typeof obj[ogKey] === 'object') { newObj[ogKey] = replaceKeysInObj(obj[ogKey], key, newKey); } else { newObj[ogKey] = obj[ogKey] } } return newObj};
Here is a breakdown of the above function
Note - The three parameters are going to be the original object(obj), the key we are going to change(key), and the new key we are going to use to replace the old key(newKey).
First: we create a new variable(newObj)and set it to an object literal({}). We will use this new object for creating our new and improved key in object.
Second:
for (var ogKey in obj){
if(ogKey === key) {
newObj[newKey] = obj[ogKey]
We use a for in loop to see if the key in the object(ogKey) matches the key we are looking to replace(key). If it does, then we are setting the new object key to the old object key.
Third: time to use recursion
else if (typeof obj[ogKey] === 'object') {
newObj[ogKey] = replaceKeysInObj(obj[ogKey], key, newKey);
If the type of value for the objects original key is an object, then we set the value equal to the recursive case so it will look inside that object as well which is not just helpful... it's AWESOME.
Forth:
else {
newObj[ogKey] = obj[ogKey]
}
The final else, if the first two conditions aren't met, will set the new objects key/value equal to the original objects key/value. This will allow the rest of the objects keys that do not match the "newKey" to stay the same after the recursive calls.
Fifth & Final:
return newObj
};
We return the new object that has our updated key inside.
There is always another way to skin a cat (lookup Object.assign) but this way way allows you to check through nested objects with the power of recursion!.
Original Link: https://dev.to/eellin6/manipulating-keys-in-an-object-using-recursion-2cb7
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To