如何在PowerShell中将数组转为动态对象?是否有类似reduce的函数?
PowerShell实现类似JavaScript reduce的对象转换
问题背景
给定如下JSON数组:
$json = [ { "name": "Name", "value": "Mike" }, { "name": "Age", "value": 25 }, { "name": "IsMarried", "value": true } ]
期望转换为如下结构的JSON:
{ "Name": "Mike", "Age": 25, "IsMarried": true }
在JavaScript中可以通过reduce方法快速实现:
const result = json.reduce((acc, { name, value }) => { acc[name] = value; return acc; }, {})
请问PowerShell中是否有类似reduce的函数?如何实现相同的转换效果?
实现方案
PowerShell中可以通过多种方式实现类似reduce的聚合逻辑,以下是几种常用方法:
1. 手动遍历累加(最贴近reduce逻辑)
先将JSON转换为PowerShell对象数组,然后用ForEach-Object维护一个哈希表作为累加器,逐个添加键值对:
# 解析JSON为PowerShell对象 $jsonObj = $json | ConvertFrom-Json # 初始化哈希表作为累加器 $result = @{} # 遍历每个对象,填充哈希表 $jsonObj | ForEach-Object { $result[$_.name] = $_.value } # 转换为JSON输出 $result | ConvertTo-Json
2. 利用Measure-Object简化实现(PowerShell 5.1+)
PowerShell的Measure-Object命令支持-AsHashTable和-Key参数,可以直接将对象数组转换为以指定属性为键的哈希表:
$jsonObj = $json | ConvertFrom-Json $result = $jsonObj | Measure-Object -Property value -AsHashTable -Key name $result | ConvertTo-Json
3. 调用.NET Linq的Aggregate方法
直接使用.NET的Linq聚合方法,和JavaScript的reduce逻辑完全一致:
$jsonObj = $json | ConvertFrom-Json $result = [Linq.Enumerable]::Aggregate($jsonObj, @{}, [Func[hashtable, object, hashtable]]{ param($acc, $item) $acc[$item.name] = $item.value return $acc }) $result | ConvertTo-Json
内容的提问来源于stack exchange,提问作者Cristian E.
相关产品推荐
相关产品推荐

