I have a function
, it takes an object
that has bunch of properties
and eventually it creates a new object from that input object. I pass a dictionary
for field-mapping to it to tell the function what property
of the input object should be mapped and renamed to what property name of the new resulting object. So for example input object can have twenty properties but I might be only interested in having a new object with five properties and new names for those properties so this way I will have a map with five properties in it.
My function works and you are more than welcome to make it better or more efficient too.
But my main question is why the order of properties in the result is not the same as the order of keys of my field-map dictionary.
Here is the code and data to recreate it:
function Convert-APIObjectToCustomObject {
param (
[Array]$dataFromAPI,
[Hashtable]$fieldMap
)
$resultData = @()
foreach ($item in $dataFromAPI) {
$newObject = New-Object -TypeName PSCustomObject
foreach ($key in $fieldMap.Keys) {
$matchedProperty = $item.PSObject.Properties | Where-Object { $_.Name.ToLower() -eq $fieldMap[$key].ToLower() }
if ($matchedProperty) {
$propertyValue = $matchedProperty.Value
} else {
Write-Warning "Property '$($fieldMap[$key])' not found on the input object. Setting default value."
$propertyValue = $null # or you can set it to '' for an empty string
}
$newObject | Add-Member -MemberType NoteProperty -Name $key -Value $propertyValue
}
$resultData += $newObject
}
return $resultData
}
# Example usage:
$dataFromAPI = @(
[PSCustomObject]@{ InstrumentId='1'; ServiceLayer='Service1'; MaturityDate=1; Gheimat='5' ; ExtraCol = '45' },
[PSCustomObject]@{ InstrumentId='2'; ServiceLayer='Service2'; MaturityDate=2; Gheimat='17'; ExtraCol = '1000'},
[PSCustomObject]@{ InstrumentId='3'; ServiceLayer='Service1'; MaturityDate=1; Gheimat='3' ; ExtraCol = 'Hi'},
[PSCustomObject]@{ InstrumentId='4'; ServiceLayer='Service1'; MaturityDate=1; Gheimat='7' ; ExtraCol = 'Hello' }
)
$fieldsMap = @{
"Id" = "InstrumentId"
"Service" = "ServiceLayer"
"Propertyx" = "MaturityDate"
"Price" = "Gheimat"
}
$resultData2 = Convert-APIObjectToCustomObject -dataFromAPI $dataFromAPI -fieldMap $fieldsMap
so I want the order of properties appearing on my result be the same as the order if "keys"
I have defined in my fieldMap
. But currently it is not. How can I do that?