From PairsLoading saved progress…

From Pairs

Implement fromPairs(pairs) — take an array of [key, value] tuples and build a single object from them. It's the exact inverse of Object.entries: where entries turns an object into a list of pairs, fromPairs turns that list back into an object. This mirrors Lodash's _.fromPairs.

Signature

// pairs:   Array<[key, value]>  — each element is a two-item tuple:
//                                 index 0 is the key, index 1 is the value.
// returns: object
//   An object where each pair's key maps to its value. Keys are object keys,
//   so they coerce to strings. On duplicate keys, the LAST pair wins.
function fromPairs(pairs): object;

Examples

// Each tuple becomes one key-value entry.
fromPairs([['a', 1], ['b', 2]]);
// → { a: 1, b: 2 }
// Duplicate keys: the last pair overwrites earlier ones.
fromPairs([['x', 1], ['x', 9]]);
// → { x: 9 }

Notes

  • Each element is a two-item tuple. Index 0 is the key, index 1 is the value. The value can be anything — a number, a string, an object, an array, null.
  • Keys become strings. Object keys are always strings, so fromPairs([[1, 'a']]) gives { '1': 'a' }, and result[1] and result['1'] reach the same entry.
  • Last pair wins on duplicates. If two pairs share a key, the later one overwrites the earlier value.
  • Empty in, empty out. fromPairs([]) returns {}.
  • Don't mutate the input. Read the pairs; build a fresh result object.
Loading editor…