Last active
December 19, 2022 20:08
-
-
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'}}`
This file contains 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
// 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