Skip to content

Instantly share code, notes, and snippets.

@ericcchiu
Created October 22, 2021 01:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ericcchiu/68e38f8d73663e30cd8b8b6eb37fa0dd to your computer and use it in GitHub Desktop.
Save ericcchiu/68e38f8d73663e30cd8b8b6eb37fa0dd to your computer and use it in GitHub Desktop.
DeepFreezeObjectRecursive
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