Converting array of objects into Object (v4)

Revision 4 of this benchmark created on


Description

https://stackoverflow.com/questions/19874555/how-do-i-convert-array-of-objects-into-one-object-in-javascript

Setup

let arr = [];
for (i = 0; i < 1000; i++) {
  arr[i] = {key: i, value: i+1}
}


function objarr2obj(ar, {key, value}) {
    const redfunc = (obj, item) => (obj[item[key]] = item[value], obj)
	return ar.reduce(redfunc, {})
}

Teardown



Test runner

Ready to run.

Testing in
TestOps/sec
using Array.reduce
const objc = arr.reduce((obj, item) => { obj[item.key] = item.value; return obj} ,{});
ready
using Object.fromEntries
const objc = Object.fromEntries(arr.map(item => [item.key, item.value]));
ready
using Array.reduce shortened
const objc = arr.reduce((obj, item) => (obj[item.key] = item.value, obj), {});
ready
using Array.reduce shortened (wrapped into func)
const objc = objarr2obj(arr, {key: 'key', value: 'value'})
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.