Abdullah Jibaly
Abdullah Jibaly

Reputation: 54810

Create object from array of keys and values

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"}

Upvotes: 9

Views: 9985

Answers (5)

jq170727
jq170727

Reputation: 14715

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

Upvotes: 0

boris.pou
boris.pou

Reputation: 372

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.

Upvotes: 1

Jeff Mercado
Jeff Mercado

Reputation: 134571

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])

Upvotes: 3

peak
peak

Reputation: 116957

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
}

Upvotes: 2

Abdullah Jibaly
Abdullah Jibaly

Reputation: 54810

Resolved this on github:

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

Upvotes: 10

Related Questions