I need to sort properties by keys on all nesting levels. The problem occurs when I'm trying to reconstruct a structure of the original object. For some reason, $keyFull is treated as a key name, not a path. And I get output "main.nested": {}
tho expected "main": { "nested": {} }
. Where's my failure? Thanks!
Code
function sortAlphabeticallyRecursive( $hashtable )
{
$sorted = [Ordered] @{ }
function sortNested
{
param(
[System.Object] $hashtable,
[String] $keyFull
)
$hashtable.keys | ForEach-Object {
if( $hashtable.$($_).Keys ) {
if( $keyFull ) {
$keyFull = "$keyFull.$_"
}
else {
$keyFull = "$_"
}
if( ! $sorted.$($keyFull) ) {
$sorted.$($keyFull) = @{}
}
sortNested $hashtable.$($_) "$keyFull"
}
else {
$hashtable.keys | ForEach-Object {
( $hashtable.GetEnumerator() | sort key ) | ForEach-Object {
$sorted.($keyFull).($_.key) = $_.value
}
}
}
}
}
sortNested( $hashtable, $null )
return $sorted
}
$hashtable = @{ 'main' = @{
'nested' = @{
'aba' = '2';
'aaa' = '1';
'aca' = '3'
}
} }
$sorted = sortAlphabeticallyRecursive( $hashtable )
$sorted | ConvertTo-Json -Depth 100
Output
{
"main": {},
"main.nested": {
"aca": "3",
"aba": "2",
"aaa": "1"
}
}
Expected
{
"main": {
"nested": {
"aca": "3",
"aba": "2",
"aaa": "1"
}
}
}