Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}
like image 544
Abdullah Jibaly Avatar asked Jan 23 '15 05:01

Abdullah Jibaly


People also ask

How do you turn an array into an object?

To convert an array to an object, use the reduce() method to iterate over the array, passing it an object as the initial value. On each iteration, assign a new key-value pair to the accumulated object and return the result. Copied! const arr = ['zero', 'one', 'two']; const obj4 = arr.

How do you assign an array to an object key?

To convert an array's values to object keys:Use the reduce() method to iterate over the array. On each iteration, assign the array element as a key in the accumulator object. The reduce method will construct an object from the array's values.

How do you create an object with two arrays?

To create an object from two arrays:Use the reduce() method to iterate over the first array. Provide an empty object as the initial value for the accumulator. Using the index, assign the key-value pair to the accumulated object. Return the result.

How do you get keys from array of objects in JS?

For getting all of the keys of an Object you can use Object. keys() . Object. keys() takes an object as an argument and returns an array of all the keys.


1 Answers

Resolved this on github:

.[0] as $keys |
.[1] as $values |
reduce range(0; $keys|length) as $i  ( {}; . + { ($keys[$i]): $values[$i] })
like image 80
Abdullah Jibaly Avatar answered Nov 02 '22 23:11

Abdullah Jibaly