Skip to content

Instantly share code, notes, and snippets.

@orimdominic
Created July 6, 2023 08:23
Show Gist options
  • Save orimdominic/3ef76da2732d8c0ea27ea8070d1d8714 to your computer and use it in GitHub Desktop.
Save orimdominic/3ef76da2732d8c0ea27ea8070d1d8714 to your computer and use it in GitHub Desktop.
Recursively iterate over an object to return an array of all the paths in the object
function extractPropsToArray(obj, arr = [], path = "") {
for (const key in obj) {
if (Object.hasOwnProperty.call(obj, key)) {
const element = obj[key];
const isObject = typeof element === "object";
if (isObject) {
const pathname = Boolean(path) ? `${path}.${key}` : `${key}`
extractPropsToArray(element, arr,pathname )
} else {
const pathname = Boolean(path) ? `${path}.${key}` : `${key}`
arr.push(pathname);
}
}
}
return arr;
}
/* For an object like
{
message: "Businesses gotten successfully",
data: {
docs: [
{
_id: "64243cebfc3c14b0649693fa",
name: "New Business ltd",
createdAt: "2023-03-29T13:28:11.396Z",
industry: "Salad",
location: "Netherlands",
totalTasks: 21,
totalCompletedTasks: 0,
},
],
totalDocs: 1,
page: 1,
prevPage: null,
nextPage: null,
totalPages: 1,
},
}
we should get the return value
[ 'message',
'data.docs.0._id',
'data.docs.0.name',
'data.docs.0.createdAt',
'data.docs.0.industry',
'data.docs.0.location',
'data.docs.0.totalTasks',
'data.docs.0.totalCompletedTasks',
'data.totalDocs',
'data.page',
'data.totalPages' ]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment