Last active
June 4, 2021 06:13
-
-
Save Parables/fda67380a90d207f34df7e3658cbc374 to your computer and use it in GitHub Desktop.
Set a deeply nested value or get the value of a deeply nested key using dot-separated-string path. E.g: 'some.deeply.nested.key'
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
| let data: Record<string, any> = { initial: "something" } | |
| let key = "root.field.subField" | |
| const setNestedValue = (obj: Record<string, any>, path: string, value) => { | |
| return path.split(".") | |
| .reduce((acc, cur, index, arr) => index === arr.length - 1 ? acc[cur] = value : acc[cur] = {}, obj) | |
| } | |
| const getNestedValue = (obj: Record<string, any>, path: string, defaultValue?: any) => | |
| path.split('.').reduce((acc, cur) => (acc ? acc[cur] : defaultValue), obj); | |
| setNestedValue(data, key, "Some Nested Value") | |
| setNestedValue(data, "just", "Some Value") | |
| function flatternKeys(obj: Record<string, any>, prefix?: string, allowNullorUndefined: boolean = false, allowFalsyValue: boolean = true): any { | |
| return Object.keys(obj).flatMap((key, i, arrr) => { | |
| let path = prefix ? `${prefix}.${key}` : key | |
| return !obj[key] ? (obj[key] === 0 || obj[key] === NaN) && allowFalsyValue ? [key] : allowNullorUndefined ? [key] : [] : typeof obj[key] !== "object" | |
| ? [key] | |
| : [path, ...flatternKeys(obj[key], path, allowNullorUndefined, false)] | |
| }) | |
| } | |
| let data = { | |
| ignoreMe: NaN, | |
| zeroThat: 0, | |
| initial: "something", | |
| just: "Some Value", | |
| root: { | |
| field: { | |
| subField: { | |
| someArr: [], | |
| notMe: undefined, | |
| neitherMe: null, | |
| ignoreMe: NaN, | |
| zeroThat: 0, | |
| last:"Some Nested Value"} | |
| } | |
| } | |
| } | |
| console.log("res", flatternKeys(data)) | |
| console.log(data) | |
| console.log(getNestedValue(data, key, undefined)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment