Create object from array of keys and values

[亡魂溺海] 提交于 2019-12-23 12:45:22

问题


I've been banging my head against the wall for several hours on this and just can't seem to find a way to do this. I have an array of keys and an array of values, how can I generate an object? Input:

[["key1", "key2"], ["val1", "val2"]]

Output:

{"key1": "val1", "key2": "val2"}

回答1:


Resolved this on github:

.[0] as $keys |
.[1] as $values |
reduce range(0; $keys|length) as $i  ( {}; . + { ($keys[$i]): $values[$i] })



回答2:


The current version of jq has a transpose filter that can be used to pair up the keys and values. You could use it to build out the result object rather easily.

transpose | reduce .[] as $pair ({}; .[$pair[0]] = $pair[1])



回答3:


Just to be clear:

(0) Abdullah Jibaly's solution is simple, direct, efficient and generic, and should work in all versions of jq;

(1) transpose/0 is a builtin in jq 1.5 and has been available in pre-releases since Oct 2014;

(2) using transpose/0 (or zip/0 as defined above), an even shorter but still simple, fast, and generic solution to the problem is:

transpose | map( {(.[0]): .[1]} ) | add

Example:

$ jq 'transpose | map( {(.[0]): .[1]} ) | add'

Input:

[["k1","k2","k3"], [1,2,3] ]

Output:

{
  "k1": 1,
  "k2": 2,
  "k3": 3
}



回答4:


Scratch this, it doesn't actually work for any array greater than size 2.

[map(.[0]) , map(.[1])] | map({(.[0]):.[1]}) | add

Welp, I thought this would be easy, having a little prolog experience... oh man. I ended up banging my head against a wall too. Don't think I'll ever use jq ever again.




回答5:


Here is a solution which uses reduce with a state object holding an iteration index and a result object. It iterates over the keys in .[0] setting corresponding values in the result from .[1]

  .[1] as $v
| reduce .[0][] as $k (
   {idx:0, result:{}}; .result[$k] = $v[.idx] | .idx += 1
  )
| .result


来源:https://stackoverflow.com/questions/28103489/create-object-from-array-of-keys-and-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!