Skip to content

Instantly share code, notes, and snippets.

@mreed4
Created March 5, 2025 04:19
Show Gist options
  • Save mreed4/bdad208a3d7c1dac39217a64da2f2904 to your computer and use it in GitHub Desktop.
Save mreed4/bdad208a3d7c1dac39217a64da2f2904 to your computer and use it in GitHub Desktop.
/*
Input is a two-level nested object with values of all keys at all levels set to "" (a blank string). Output is another object, same level of nesting, with all values at all levels set to another string (or--as I used it--as to a class instantiation, etc.)
I built this for a specific purpose, for a much larger project.
This can/should probably be refactored to allow for it to work beyond two levels of nesting. Perhaps this could be accomplished via recursion, or perhaps via a wrapper for loop.
*/
function updateObjectValues(obj) {
let entries = Object.entries(obj);
let arr = [];
let subArr = [];
let desiredThing = "New value"; // Every value will be replaced with this
entries.forEach((entry) => {
let key = entry[0];
let value = entry[1]; // In the scope of this repl, this is either a string or an object
let isString = typeof value === "string";
if (isString) {
arr.push([key, desiredThing]);
} else {
let subEntries = Object.entries(value);
subEntries.forEach((subEntry) => {
let subKey = subEntry[0];
subArr.push([subKey, desiredThing]);
});
arr.push([key, Object.fromEntries(subArr)]);
}
});
newObj = Object.fromEntries(arr);
return newObj;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment