JavaScriptEasy
Convert an array of pairs to an object
Use Object.fromEntries(pairs), which turns an iterable of [key, value] pairs into an object (later duplicate keys win); write a reduce or loop version when you need validation, custom duplicate handling, or nested keys.
Details
- Works with any iterable of pairs: arrays,
Map(Object.fromEntries(map)),URLSearchParams, generator output. - Keys are converted to strings (symbols stay symbols).
- Duplicate keys: the last pair wins. If you need all values, group them into arrays instead.
- It is the inverse of
Object.entries, which makesObject.fromEntries(Object.entries(obj).map(...))the standard way to transform an object's keys or values.
Safety with untrusted keys
Keys like "__proto__" can be risky when you assign them into a normal object with obj[key] = value in a loop, because obj["__proto__"] = ... changes the prototype (prototype pollution). Object.fromEntries defines own properties, so "__proto__" becomes a normal key, and a Map or Object.create(null) is also safe.
Variations
- Validate pairs (each must be a 2-item array).
- Group duplicates into arrays:
[["tag","a"],["tag","b"]]→{ tag: ["a","b"] }. - Nested keys with dot paths:
[["user.name","Ada"]]→{ user: { name: "Ada" } }.
Code example
js
1const pairs = [["name", "Ada"], ["role", "admin"], ["level", 3], ["role", "owner"]];2console.log(Object.fromEntries(pairs)); // { name: "Ada", role: "owner", level: 3 } - last duplicate wins34// From a Map and from query parameters5console.log(Object.fromEntries(new Map([["a", 1], ["b", 2]]))); // { a: 1, b: 2 }6console.log(Object.fromEntries(new URLSearchParams("q=js&page=2"))); // { q: "js", page: "2" }78// Transform an object via entries9const prices = { pen: 2, book: 12 };10console.log(Object.fromEntries(Object.entries(prices).map(([k, v]) => [k.toUpperCase(), Math.round(v * 1.2 * 100) / 100]))); // { PEN: 2.4, BOOK: 14.4 }1112// Manual version with validation and grouping of duplicates13function pairsToObject(input, { groupDuplicates = false } = {}) {14 const out = Object.create(null);15 for (const pair of input) {16 if (!Array.isArray(pair) || pair.length !== 2) throw new TypeError(`Invalid pair: ${JSON.stringify(pair)}`);17 const [key, value] = pair;18 if (groupDuplicates && key in out) out[key] = [].concat(out[key], value);19 else out[key] = value;20 }21 return out;22}23console.log({ ...pairsToObject([["tag", "js"], ["tag", "ts"], ["id", 1]], { groupDuplicates: true }) }); // { tag: ["js", "ts"], id: 1 }2425// Nested keys with dot paths26const toNested = (entries) =>27 entries.reduce((obj, [path, value]) => {28 const keys = path.split(".");29 keys.slice(0, -1).reduce((node, k) => (node[k] ??= {}), obj)[keys.at(-1)] = value;30 return obj;31 }, {});32console.log(toNested([["user.name", "Ada"], ["user.address.city", "London"], ["active", true]]));33// { user: { name: "Ada", address: { city: "London" } }, active: true }3435// "__proto__" stays a plain key with fromEntries36const parsed = Object.fromEntries([["__proto__", { polluted: true }]]);37console.log(({}).polluted, Object.hasOwn(parsed, "__proto__")); // undefined true
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.