Q9: Implement Custom pick and omit Object Helpers

Build pick(obj, keys) to extract specific properties into a new object, and omit(obj, keys) to create a copy that excludes specified keys.

Object Pick and Omit Utility
function pick(obj, keys) {
  return keys.reduce((acc, key) => {
    if (key in obj) acc[key] = obj[key];
    return acc;
  }, {});
}

function omit(obj, keys) {
  const keySet = new Set(keys);
  return Object.keys(obj).reduce((acc, key) => {
    if (!keySet.has(key)) acc[key] = obj[key];
    return acc;
  }, {});
}

const user = { id: 1, name: 'Alex', role: 'admin' };
console.log(pick(user, ['name', 'role'])); // { name: 'Alex', role: 'admin' }
console.log(omit(user, ['role']));         // { id: 1, name: 'Alex' }
💡 pick filters down to specified keys, while omit uses a Set lookup to drop listed keys efficiently.
Key Takeaways
  • Reduces object keys dynamically.
  • Using a Set in omit allows O(1) key exclusion checks.
Knowledge Check

What is the benefit of passing keys as a Set inside the omit function?