Created
October 12, 2021 15:19
-
-
Save abhagsain/070bcca4421f49b2909bf2f417774b8a to your computer and use it in GitHub Desktop.
Convert Object Reference to String dot Notation JavaScript
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
function getStringDotRefFromObject(obj, arr = [], objPath = '') { | |
const isObject = typeof obj === 'object' && !Array.isArray(obj) && obj !== null; | |
if (!isObject) return objPath; | |
return Object.keys(obj).reduce((acc, curr) => { | |
const path = obj[curr]; | |
return acc.concat( | |
// eslint-disable-next-line prefer-template | |
getStringDotRefFromObject(path, arr, `${objPath ? objPath + '.' : ''}${curr}`) | |
); | |
}, []); | |
} | |
const result = getStringDotRefFromObject({ | |
this: { | |
is: { | |
nested: { | |
object: '' | |
} | |
} | |
}, | |
and: { | |
this: '', | |
is: { | |
a: true, | |
sibling: true, | |
} | |
} | |
}); | |
// Output - ["this.is.nested.object", "and.this", "and.is.a", "and.is.sibling"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment