Skip to content

Instantly share code, notes, and snippets.

@VladSez
Last active December 19, 2022 20:08
Show Gist options
  • Save VladSez/f484d1da0e6b5c296f7c69a426804c8b to your computer and use it in GitHub Desktop.
Save VladSez/f484d1da0e6b5c296f7c69a426804c8b to your computer and use it in GitHub Desktop.
Write to the specific key of the object -> `pathToWriteTo(['/', 'a'], 'myData')` -> `{'/': {'a': 'myData'}}`
// Write to the specific key of the object
// pathToWriteTo(['/', 'a'], 'myData')
// will write to -> {'/': {'a': 'myData'}}
function pathToWriteTo(
pathArr: string[],
input: { [key: string]: {} },
fs: { [key: string]: {} }
) {
let level: { [key: string]: {} } = fs;
let index = 0;
for (let path of pathArr) {
// if we are at last index(end of the pathArr), we should write the input
if (index === pathArr.length - 1) {
level[path] = input;
} else {
level = level[path];
}
index++;
}
}
const target = {};
pathToWriteTo(["/"], { omg: "333" }, target);
pathToWriteTo(["/", "omg"], { wow: "2323" }, target);
target.toEqual({
"omg": {
"wow": "2323"
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment