Object.fromEntriesLoading saved progress…

Object.fromEntries

Object.fromEntries is the inverse of Object.entries: it takes a list of [key, value] pairs and builds an object out of them. It's how you turn a Map into a plain object, or rebuild an object after transforming it as an array of entries.

Implement objectFromEntries(iterable). Accept any iterable of [key, value] pairs — an array of arrays, a Map, a generator — and return a plain object with one property per pair. If a key appears more than once, the last value wins.

Signature

function objectFromEntries(iterable) {
  // iterable yields [key, value] pairs; returns a plain object
  // { key: value, ... }
}

Examples

objectFromEntries([['a', 1], ['b', 2]]); // { a: 1, b: 2 }
objectFromEntries(new Map([['x', 1]]));   // { x: 1 }
// Transform an object through its entries and rebuild it:
const prices = { pen: 2, book: 10 };
const doubled = objectFromEntries(
  Object.entries(prices).map(([k, v]) => [k, v * 2]),
); // { pen: 4, book: 20 }

Notes

  • Any iterable — not just arrays. A Map, a Set of pairs, or a generator that yields pairs must all work.
  • Last key wins — if the same key appears twice, the later pair overwrites the earlier one.
  • Keys become strings — a numeric key 1 becomes the property '1', as with any object key.
  • Values are untouched — store them as-is; don't stringify or clone them.
  • Empty input — an empty iterable produces an empty object {}.
Loading editor…