Convert an array of objects to a single object

Index records by a key field.

JavaScript Version 1.0.0 · MIT · .md

convert-an-array-of-objects-to-a-single-object.js
function toObject({ values, key }) { return Object.fromEntries(values.map(item => [item[key], item])); }

Input & expected output

Input

{
  "values": [
    {
      "id": "[email protected]",
      "status": "delivered"
    },
    {
      "id": "[email protected]",
      "status": "deferred"
    }
  ],
  "key": "id"
}

Expected output

{
  "[email protected]": {
    "id": "[email protected]",
    "status": "delivered"
  },
  "[email protected]": {
    "id": "[email protected]",
    "status": "deferred"
  }
}

The edge case

Input

{
  "values": [
    {
      "id": "a",
      "n": 1
    },
    {
      "id": "a",
      "n": 2
    }
  ],
  "key": "id"
}

Expected output

{
  "a": {
    "id": "a",
    "n": 2
  }
}

Know the limits

  • A repeated key keeps the last record, as the edge case shows.
  • Uses the Object.fromEntries variant; the spread variant copies the accumulator on every item.

The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.

Source & maintenance

Based on Convert an array of objects to a single object from the original 1loc collection by Nguyen Huu Phuoc, with ChoukseyKhushbu, wenyangliu. Copyright (c) 2020 phuoc-ng. MIT licensed.

Keeps the Object.fromEntries variant. Original MDX retained as inert source evidence.

Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.

Local fixture scope · Node.js 22.23.2 · reviewed October 28, 2026. No external service is required.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.