Create an object from pairs of key and value
Turn [key, value] pairs into a plain object with Object.fromEntries.
function toObject(pairs) { return Object.fromEntries(pairs); }
Input & expected output
Input
[
[
"from",
"orders@your-verified-domain.example"
],
[
"to",
"ana@example.com"
],
[
"subject",
"Order 8812 confirmed"
]
]Expected output
{
"from": "orders@your-verified-domain.example",
"to": "ana@example.com",
"subject": "Order 8812 confirmed"
}The edge case
Input
[
[
"status",
"deferred"
],
[
"status",
"delivered"
]
]Expected output
{
"status": "delivered"
}Know the limits
- When a key repeats, the later pair wins, as the edge case shows.
- Keys become strings. A "__proto__" key becomes an ordinary own property, unlike assignment.
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 Create an object from the pairs of key and value from the original 1loc collection by Nguyen Huu Phuoc, with robinpokorny. Copyright (c) 2020 phuoc-ng. MIT licensed.
Curated Object.fromEntries variant; pair validation, repeated-key edge case and prototype-key note. Original MDX retained as inert source evidence.
Maintained by Oveyon. Original source commit: 14b481cf60df. This edition’s file: contents/create-an-object-from-the-pairs-of-key-and-value.mdx in akamind/1loc, commit 0a77f131b22d. Read the license.
Keep exploring
- Pick properties from an object — Build a new object with only the requested own properties.
- Omit properties from an object — Keep the own enumerable fields that are not in a supplied list.
- Check if multiple objects are equal — Compare JSON serializations with the first object.