Last active
April 23, 2019 19:13
-
-
Save agrublev/efdd4827d67165ecc1efa751340882d6 to your computer and use it in GitHub Desktop.
Recursive object manipulation
This file contains hidden or 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 iterateObject = (obj, executeOnValue) => { | |
Object.keys(obj).forEach(name=> { | |
let val = obj[name]; | |
if (typeof val === "object") { | |
return iterateObject(val, executeOnValue); | |
} else if (val === undefined) { | |
obj[name] = ""; | |
} else { | |
obj[name] = executeOnValue(val); | |
} | |
}); | |
}; | |
let deepObject = { | |
palette: { | |
common: { | |
black: "rgba(96, 39, 39, 1)", | |
white: "#fff" | |
}, | |
background: { | |
paper: "rgba(214, 234, 251, 1)", | |
default: "rgba(241, 246, 247, 1)" | |
}, | |
primary: { | |
light: "#7986cb", | |
main: "rgba(242, 25, 163, 1)", | |
dark: "rgba(35, 54, 178, 1)", | |
contrastText: "#fff" | |
}, | |
secondary: { | |
light: "#ff4081", | |
main: "rgba(139, 17, 246, 1)", | |
dark: "#c51162", | |
contrastText: "#fff" | |
} | |
} | |
}; | |
iterateObject(deepObject, value => { | |
if (value.includes("rgba")) { | |
return "---"+value; | |
} else { | |
return value; | |
} | |
}); | |
console.warn("Updated object", deepObject); | |
// Yields | |
/* | |
{ | |
palette: { | |
common: { black: "---rgba(96, 39, 39, 1)", white: "#fff" }, | |
background: { | |
paper: "---rgba(214, 234, 251, 1)", | |
default: "---rgba(241, 246, 247, 1)" | |
}, | |
primary: { | |
light: "#7986cb", | |
main: "---rgba(242, 25, 163, 1)", | |
dark: "---rgba(35, 54, 178, 1)", | |
contrastText: "#fff" | |
}, | |
secondary: { | |
light: "#ff4081", | |
main: "---rgba(139, 17, 246, 1)", | |
dark: "#c51162", | |
contrastText: "#fff" | |
} | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment