Skip to content

Instantly share code, notes, and snippets.

@abhagsain
Created October 12, 2021 15:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhagsain/070bcca4421f49b2909bf2f417774b8a to your computer and use it in GitHub Desktop.
Save abhagsain/070bcca4421f49b2909bf2f417774b8a to your computer and use it in GitHub Desktop.
Convert Object Reference to String dot Notation JavaScript
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