Created
October 22, 2021 01:58
-
-
Save ericcchiu/68e38f8d73663e30cd8b8b6eb37fa0dd to your computer and use it in GitHub Desktop.
DeepFreezeObjectRecursive
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
const sampleObject = { | |
author: "J.R.R. Tolkien", | |
genre: "Sci-Fi/Fantasy", | |
birthday: "January 3, 1892", | |
books: [ | |
{ | |
title: "The Silmarillion", | |
publicationDate: 1927 | |
}, | |
{ | |
title: "The Hobbit", | |
publicationDate: { | |
uk: 1945, | |
us: 1946 | |
} | |
}, | |
{ | |
title: "The Fellowship of the Ring" | |
}, | |
{ | |
title: "The Two Towers" | |
}, | |
{ | |
title: "The Return of the King" | |
} | |
] | |
} | |
// deepFreezeObj Function | |
// Base Case: Check to see if the type of input is not an object | |
// Recursive: If inputObj at this point is still an object | |
// Call deep freeze object | |
const deepFreezeObj = inputObj => { | |
if (typeof inputObj !== 'object') return; | |
// console.log(Object.values(inputObj)); | |
Object.values(inputObj).forEach( item => { | |
// console.log('Item: ', item); | |
deepFreezeObj(item); | |
}); | |
Object.freeze(inputObj); | |
} | |
// deepFreezeObj(sampleObject); | |
console.log("INITIAL" + JSON.stringify(sampleObject, null, 4)); | |
Object.freeze(sampleObject); | |
sampleObject.author = "JK Rowling"; | |
sampleObject.books[1].publicationDate.uk = 1999; | |
console.log("FINAL" + JSON.stringify(sampleObject, null, 4)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment