Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JavaScript array of 2 element arrays into object key value pairs

Tags:

What is the fastest algorithm for getting from something like this:

var array = [ [1,'a'], [2,'b'], [3,'c'] ]; 

to something like this:

Object { 1: "a", 2: "b", 3: "c" } 

so far this is what i've come up with:

function objectify(array) {     var object = {};     array.forEach(function(element) {         object[element[0]] = element[1];     });     return object; } 

which works fine, but it seems kind of clumsy. Is there a better way? Would something like reduce() work and would that be any faster?

like image 232
Fred Guest Avatar asked Oct 19 '14 19:10

Fred Guest


People also ask

How do you create an array of objects from two arrays?

To create an object from two arrays:Use the Array. forEach() method to iterate over the first array. Use the index to access the element from the second array. On each iteration, assign the key-value pair to an object.

How would you create an object from an array of key-value pairs?

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 split an array into array pairs in JavaScript?

To do this, we call reduce with a callback that returns the result array that's created from the result array spread into a new array and an array with the next 2 items in the list if index is event. We get the next 2 items with the slice with index and index + 2 as the indexes. Otherwise, we just return result .

How do you convert an object to a key-value pair?

To convert a JavaScript object into a key-value object array, we can use the Object. entries method to return an array with of key-value pair arrays of a given object. Then we can use the JavaScript array map method to map the key-value pair arrays into objects.


1 Answers

With Object.fromEntries, you can convert from Array to Object:

var array = [    [1, 'a'],    [2, 'b'],    [3, 'c']  ];  var object = Object.fromEntries(array);  console.log(object);
like image 171
Penny Liu Avatar answered Sep 21 '22 15:09

Penny Liu