jQuery中的SQL Join模拟 [英] Analogue for sql join in jq
本文介绍了jQuery中的SQL Join模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下json:
[
{"id": "1", "type": "folder", "title": "folder-1"},
{"id": "2", "type": "folder", "title": "folder-2"},
{"id": "3", "type": "item", "title": "item-1", "folder": "1"},
{"id": "4", "type": "item", "title": "item-2", "folder": "2"},
{"id": "5", "type": "item", "title": "item-3"}
]
基本上,我需要使用jq生成此输出,这类似于sql join的结果:
Basically, I need to produce this output using jq, which is similar to the result of sql join:
[
{"type": "item", "title": "item-1", "folder": "folder-1"},
{"type": "item", "title": "item-2", "folder": "folder-2"},
{"type": "item", "title": "item-3"}
]
有什么想法吗?
推荐答案
尝试使用此过滤器:
map(
(select(.type=="item") | { key: .folder, value: { type, title } }),
(select(.type=="folder") | { key: .id, value: { folder: .title } })
)
| group_by(.key)
| map(
(map(select(.key != null) | .value) | add)
// map(.value)[]
)
您必须将其分解为几个步骤.
You'll have to break this out into steps.
-
获取项目和文件夹,并为每个项目和文件夹获取您感兴趣的值,并为其分配要关联的密钥.
Get the items and folders and for each, take the values you're interested in and assign it a key to associate with.
map(
(select(.type=="item") | { key: .folder, value: { type, title } }),
(select(.type=="folder") | { key: .id, value: { folder: .title } })
)
按键将所有分组
Group all by the key
| group_by(.key)
然后将包含键(文件夹)的值与其他值组合
Then combine the values that have keys (folders) and the value otherwise
| map(
(map(select(.key != null) | .value) | add)
// map(.value)[]
)
这篇关于jQuery中的SQL Join模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文