# Convert an array of objects to a single object

Index records by a key field.

Canonical: https://1loc.dev/array/convert-an-array-of-objects-to-a-single-object/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Local fixtures; no external services
Updated: 2026-10-28

## Implementation

```javascript
function toObject({ values, key }) { return Object.fromEntries(values.map(item => [item[key], item])); }
```

## Input

```json
{
  "values": [
    {
      "id": "ana@example.com",
      "status": "delivered"
    },
    {
      "id": "rui@example.com",
      "status": "deferred"
    }
  ],
  "key": "id"
}
```

## Expected output

```json
{
  "ana@example.com": {
    "id": "ana@example.com",
    "status": "delivered"
  },
  "rui@example.com": {
    "id": "rui@example.com",
    "status": "deferred"
  }
}
```

## Edge case

Input:
```json
{
  "values": [
    {
      "id": "a",
      "n": 1
    },
    {
      "id": "a",
      "n": 2
    }
  ],
  "key": "id"
}
```
Output:
```json
{
  "a": {
    "id": "a",
    "n": 2
  }
}
```

## 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 lab validates types and size before calling this function. Add equivalent validation at your own trust boundary.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/convert-an-array-of-objects-to-a-single-object.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: ChoukseyKhushbu, wenyangliu
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Keeps the Object.fromEntries variant. Original MDX retained as inert source evidence.
