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"}
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.
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.
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.
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.
Resolved this on github:
.[0] as $keys |
.[1] as $values |
reduce range(0; $keys|length) as $i ( {}; . + { ($keys[$i]): $values[$i] })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With