Skip to content

Instantly share code, notes, and snippets.

@thomaspatrickwelborn
Last active May 13, 2025 02:02
Show Gist options
  • Save thomaspatrickwelborn/b9452ff0d5cc4527d4760e8e1cfd7342 to your computer and use it in GitHub Desktop.
Save thomaspatrickwelborn/b9452ff0d5cc4527d4760e8e1cfd7342 to your computer and use it in GitHub Desktop.
Property Directory
const Accessors = {
object: ($target, $property) => {
if($property === undefined) { return $target }
else { return $target[$property] }
},
map: ($target, $property) => {
if($property === undefined) { return $target }
else { return $target.get($property) }
},
}
const Options = {
maxDepth: 10,
accessors: [Accessors.object],
}
export default function propertyDirectory($object, $options) {
const _propertyDirectory = []
const options = Object.assign({}, Options, $options)
let { maxDepth, accessors, values } = options
options.depth = options.depth++ || 0
if(options.depth > maxDepth) { return _propertyDirectory }
iterateAccessors:
for(const $accessor of accessors) {
const object = $accessor($object)
if(!object) continue iterateAccessors
iterateObjectProperties:
for(const [$key, $value] of Object.entries(object)) {
if(!values) { _propertyDirectory.push($key) }
else if(values) { _propertyDirectory.push([$key, $value]) }
if(
typeof $value === 'object' &&
$value !== null &&
$value !== object
) {
const subtargets = propertyDirectory($value, options)
if(!values) {
for(const $subtarget of subtargets) {
const path = [$key, $subtarget].join('.')
_propertyDirectory.push(path)
}
}
else if(values) {
for(const [$subtargetKey, $subtarget] of subtargets) {
const path = [$key, $subtargetKey].join('.')
_propertyDirectory.push([path, $subtarget])
}
}
}
}
}
return _propertyDirectory
}
@thomaspatrickwelborn
Copy link
Author

thomaspatrickwelborn commented Feb 25, 2025

Input:

propertyDirectory({
  propertyA: {
    propertyB: {
      propertyC: 333
    },
    propertyD: "333",
  },
  propertyE: false
})

Output:

[
  "propertyA",
  "propertyA.propertyB",
  "propertyA.propertyB.propertyC",
  "propertyA.propertyD",
  "propertyE"
]

@thomaspatrickwelborn
Copy link
Author

Input:

Object.fromEntries(
  propertyDirectory({
    propertyA: {
      propertyB: {
        propertyC: 333
      },
      propertyD: "333",
    },
    propertyE: false
  }, { values: true })
)

Output:

{
  "propertyA": {
    "propertyB": {
      "propertyC": 333
    },
    "propertyD": "333"
  },
  "propertyA.propertyB": {
    "propertyC": 333
  },
  "propertyA.propertyB.propertyC": 333,
  "propertyA.propertyD": "333",
  "propertyE": false
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment