英文:
Transfer two array content values of same count into key value pair
问题
我有一个问题。
假设我有一个像这样的 JSON 文档:
{
"counts": [
17,
1014,
22,
9,
11
],
"values": [
"5",
"10",
"15",
"20",
"25"
]
}
我想要得到这样的结果:
{
"5": 17,
"10": 1014,
"15": 22,
"20": 9,
"25": 11
}
基本上是将数组元素依次分配为键值对。我该如何实现这个目标?
我尝试了 jq 的 with_entries(.values = .counts)
和 with_entries(.values[] = .counts[])
,但它们都没有生效。
英文:
I have a question.
Let's assume I had a json doc like this:
{
"counts": [
17,
1014,
22,
9,
11
],
"values": [
"5",
"10",
"15",
"20",
"25"
]
}
and I wanted to get a result like this:
{
"5":17,
"10":1014,
"15":22,
"20":9,
"25":11
}
basically the array elements assigned as key value pairs one after the other. How can I achieve that?
I tried jq with_entries(.values = .counts)
and with_entries(.values[] = .counts[])
but it didn't work.
答案1
得分: 3
I'd use transpose
with reduce
:
[ .counts, .values ] | transpose | reduce .[] as $t ({}; .[$t[1]] = $t[0])
Output:
{
"5": 17,
"10": 1014,
"15": 22,
"20": 9,
"25": 11
}
英文:
I'd use transpose
with reduce
:
[ .counts, .values ] | transpose | reduce .[] as $t ({}; .[$t[1]] = $t[0])
Output:
{
"5": 17,
"10": 1014,
"15": 22,
"20": 9,
"25": 11
}
Online Demo
答案2
得分: 3
以下是两种不使用transpose
的解决方案:
[(.counts | keys[]) as $i | {(.values[$i]): .counts[$i]}] | add
. as {$values} | .counts | with_entries(.key |= $values[.])
输出:
{
"5": 17,
"10": 1014,
"15": 22,
"20": 9,
"25": 11
}
英文:
Here are two transpose
-free solutions:
[(.counts | keys[]) as $i | {(.values[$i]): .counts[$i]}] | add
. as {$values} | .counts | with_entries(.key |= $values[.])
Output:
{
"5": 17,
"10": 1014,
"15": 22,
"20": 9,
"25": 11
}
答案3
得分: 0
基于@pmf的答案,这里有一些改进:
. as $in
| reduce (.values|keys[]) as $i (
{};
.[$in.values[$i]] = $in.counts[$i]
)
它避免了在with_entries
中隐藏的一些中间对象,或者在add
之前明显可见的对象,并直接转到了reduce
,reduce
也被with_entries
和add
同时使用。它避免了一些中间步骤。
英文:
Based on @pmf's answer here is a slight improvement:
. as $in
| reduce (.values|keys[]) as $i (
{};
.[$in.values[$i]] = $in.counts[$i]
)
It avoids some intermediate objects either hidden in with_entries
or plain
visible before the add
and goes directly to reduce
which is also used both by with_entries
and add
.
It avoids
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论