I have:
var keys = [ "height", "width" ]; var values = [ "12px", "24px" ];
And I'd like to convert it into this object:
{ height: "12px", width: "24px" }
In Python, there's the simple idiom dict(zip(keys,values))
. Is there something similar in jQuery or plain JavaScript, or do I have to do this the long way?
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.
The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.
Use the Array. We can use the JavaScript array reduce method to combine objects in an array into one object. We have the arr array which we want to combine into one object. To do that, we call reduce with a callback that returns an object with obj spread into the returned object. And we add the item.
The simplest ES6 one-liner solution using Array reduce
:
const keys = ['height', 'width']; const values = ['12px', '24px']; const merged = keys.reduce((obj, key, index) => ({ ...obj, [key]: values[index] }), {});
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