将两个具有相同数量的数组内容值转换为键值对。

huangapple go评论72阅读模式
英文:

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
}

Online Demo

英文:

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

Demo

. as {$values} | .counts | with_entries(.key |= $values[.])

Demo

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之前明显可见的对象,并直接转到了reducereduce也被with_entriesadd同时使用。它避免了一些中间步骤。

英文:

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

huangapple
  • 本文由 发表于 2023年6月27日 17:37:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76563529.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定