Powershell中如何将数组归约为动态对象

owfi6suc  于 2022-12-13  发布在  Shell
关注(0)|答案(1)|浏览(107)

我有一个JSON数组,如下所示:

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

预期输出如下:

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

在javascript中,我会这样做:
const result = json.reduce((acc, { name, value }) => { acc[name] = value; return acc; }, {})

问题:

是否存在类似reduce的函数?如何实现相同的效果?

uyto3xhc

uyto3xhc1#

要'合并'数组项,我会使用一个有序的哈希表如下:

$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

结果:

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

相关问题