Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge keys array and values array into an object in JavaScript

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?

like image 480
itsadok Avatar asked Jul 13 '09 06:07

itsadok


People also ask

How do you convert two arrays into objects?

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 can I merge two arrays in JavaScript?

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.

How do I merge an array of objects into one?

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.


1 Answers

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] }), {}); 
like image 143
Yiin Avatar answered Sep 17 '22 14:09

Yiin