Skip to content

Instantly share code, notes, and snippets.

@nikoheikkila
Created March 1, 2023 17:14
Show Gist options
  • Save nikoheikkila/273c97f06c2a7a23b58f622f143972f6 to your computer and use it in GitHub Desktop.
Save nikoheikkila/273c97f06c2a7a23b58f622f143972f6 to your computer and use it in GitHub Desktop.
Update TypeScript objects given a string path and a value.
const separator = ".";
const updateRecursively = <T extends Record<string, any>>(
data: T,
keys: string[],
value: unknown
): T => {
const [key] = keys;
if (keys.length === 1)
return {
...data,
[key]: value,
};
return {
...data,
[key]: updateRecursively(data?.[key] || {}, keys.slice(1), value),
};
};
const updateObject = <T extends Record<string, any>>(
data: T,
path: string,
value: unknown
): T => updateRecursively(data, path.split(separator), value);
const example1 = {};
console.log("Simple usage:", updateObject(example1, "b.c.d", 5));
const example2 = { b: { e: 8 } };
console.log("Keep the initial data: ", updateObject(example2, "b.c.d", 5));
const example3 = { b: { e: 8, c: 2 } };
console.log("Override data: ", updateObject(example3, "b.c.d", 5));
const example4 = { b: { e: 8, c: 2 } };
console.log("Complex value: ", updateObject(example4, "b.c.d", { f: 12 }));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment