Last active
May 13, 2025 02:02
-
-
Save thomaspatrickwelborn/b9452ff0d5cc4527d4760e8e1cfd7342 to your computer and use it in GitHub Desktop.
Property Directory
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
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 | |
} |
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
Input:
Output: