Convert an array of objects to a single object
Index records by a key field.
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.
Keep exploring
- Clone an array — Create a new array without copying the objects inside it.
- Remove duplicate values — Keep the first occurrence of each value, in its original order.
- Flatten a nested array — Turn a nested array into one sequence of values.