Converting array of objects into Object (v6)

Revision 6 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, {})
}

function objarr2obj_naive(ar, {key, value}) {
    var res = {};		// maybe it'll be better not to imply constant-ness every time
    for (const obj of arr) {
        res[obj[key]] = obj[value]
    }
    return res
}

function objarr2obj_naive_const(ar, {key, value}) {
    const res = {};		// No it's not. const da king
    for (const obj of arr) {
        res[obj[key]] = obj[value]
    }
    return res
}

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
using unpacking for
const objc = {};
for (const {key, value} of arr.values()) {
  objc[key] = value
} 
ready
using unpacking for (wrapped into func)
const objc = objarr2obj_naive(arr, {key: 'key', value: 'value'})
ready
using unpacking for <const> (wrapped into func)
const objc = objarr2obj_naive_const(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.