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?
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.
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 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 .
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.
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);
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