Q8: Invert Keys and Values of an Object

Swap the keys and values of a plain object into a new object using a for...in loop combined with a hasOwnProperty check to ignore prototype properties.

Object Key-Value Inversion
function invertObject(obj) {
  const inverted = {};
  for (let key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      inverted[obj[key]] = key;
    }
  }
  return inverted;
}

console.log(invertObject({ a: 'x', b: 'y' })); // { x: 'a', y: 'b' }
💡 Maps each value obj[key] as a key in the new object, assigning the original key string as its value.
Key Takeaways
  • Swaps keys and values into a new object.
  • Uses hasOwnProperty guard to prevent iterating inherited prototype properties.
Knowledge Check

What happens if an object contains multiple duplicate values during inversion (e.g. { a: 1, b: 1 })?