Home > OS >  How to Reduce Array to dynamic object in Powershell
How to Reduce Array to dynamic object in Powershell

Time:11-30

I have a JSON array like this:

$json = [
  {  "name": "Name",      "value": "Mike" },
  {  "name": "Age",       "value": 25 },
  {  "name": "IsMarried", "value": true }
]

Expected output is this:

{
  "Name": "Mike",
  "Age": 25,
  "IsMarried": true
}

In javascript I would do it this way:

const result = json.reduce((acc, { name, value }) => { acc[name] = value; return acc; }, {})

Question:

Is there an existing function like reduce? How can I achieve same effect?

CodePudding user response:

To 'merge' array items like that, I would use an ordered Hashtable like below:

$json = @'
[
  {  "name": "Name",      "value": "Mike" },
  {  "name": "Age",       "value": 25 },
  {  "name": "IsMarried", "value": true }
]
'@

# create an ordered Hashtable to store the values
$combine = [ordered]@{}
($json | ConvertFrom-Json) | ForEach-Object {
    $combine[$_.Name] = $_.Value
}

# now you can leave it as Hashtable and convert it to JSON
$combine | ConvertTo-Json

# or you can convert (cast) to PsCustomObject first:
# [PsCustomObject]$combine | ConvertTo-Json

Result:

{
    "Name":  "Mike",
    "Age":  25,
    "IsMarried":  true
}
  • Related