使用jq匹配两个对象数组属性,实现作者用户名映射为真实姓名
解决方案
你只需要先将数组结构的realnames转换为用户名到真实姓名的键值对映射对象,即可复用原有实现逻辑。
写法1:使用reduce实现转换
(.realnames | reduce .[] as $item ({}; .[$item.id] = $item.name)) as $names | .posts[] | {title, author: $names[.author]}
实现逻辑:
- 遍历
realnames数组,将每个元素的id作为键、name作为值,生成和原案例结构一致的映射对象存入$names变量 - 后续遍历
posts数组替换author字段的逻辑和原写法完全相同
写法2:使用内置from_entries函数实现更简洁的转换
(.realnames | map({key: .id, value: .name}) | from_entries) as $names | .posts[] | {title, author: $names[.author]}
两种写法的输出完全一致,可根据偏好选择。
内容的提问来源于stack exchange,提问作者Daniel Kaplan
相关产品推荐
相关产品推荐

