Array to object

Benchmark created on


Setup

const array = [...Array(1000)].map((_, index) => {
  const i = index + 1
  return {
    key: `key${i + 1}`,
    value: `value${i + 1}`,
  }
})

Test runner

Ready to run.

Testing in
TestOps/sec
Reduce with assignment
const result = array.reduce((obj, item) => {
  obj[item.key] = item.value
  return obj
}, {})
ready
Reduce with Object.defineProperty
const result = array.reduce(
  (obj, item) =>
    Object.defineProperty(obj, item.key, {
      value: item.value,
      writable: true,
      enumerable: true,
      configurable: true,
    }),
  {},
)
ready
For loop with assignment
const result = {}

for (const item of array) {
  result[item.key] = item.value
}
ready
For loop with assignment
const result = {}

for (let i = 0; i < array.length; i++) {
  const item = array[i]
  result[item.key] = item.value
}
ready
For loop with assignment noncached
const result = {}

for (let i = 0; i < array.length; i++) {
  result[array[i].key] = array[i].value
}
ready

Revisions

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