
A Generic Function to Update and Manipulate Object Arrays in TypeScript

While building my newest SaaS product, ReduxPlate, I realized a common pattern kept cropping up in my array manipulation functions. I was always updating a specific value at a specific key, based on a specific test on some other key.
*Plug: Speaking of ReduxPlate, which automatically generates Redux code for you, I’m writing a book that documents every step I took along the way to build ReduxPlate, from boilerplate starters to the finished live product. I’d love it if you check it out! Yes, You’ve read this correctly! I literally build ReduxPlate from start to finish, right before your eyes — and the code is all public!
For example, for the editor widget on the ReduxPlate homepage, I use a stateful array of type IEditorSettings to determine which editor is currently active and what the actual code value is in the editor:
export default interface IEditorSetting {
fileLabel: string
code: string
isActive: boolean
}
Such behavior required me to write two event handlers:
onChangeCode for when the code changes:
const onChangeCode = (code: string) =>
{
setEditorSettingsState(editorSettingsState.map(editorSetting => {
if (editorSetting.isActive) {
editorSetting.code = code
}
return editorSetting
})
)