Back to Home
Objects

How to Pick or Omit Object Properties

Use destructuring and rest operator to pick/omit properties

Quick Answer (2024 ES6+ Way)

javascript
const user = { id: 1, name: 'Alice', email: '[email protected]', password: '***' };
const { password, ...safe } = user;
console.log(safe); // { id: 1, name: 'Alice', email: '[email protected]' }

Live Example

javascript
const user = {
  id: 123,
  username: 'alice',
  email: '[email protected]',
  password: 'secret',
  createdAt: '2024-01-01'
};

// Omit properties
const { password, createdAt, ...publicUser } = user;
console.log(publicUser);

// Pick specific properties
const pick = (obj, keys) =>
  Object.fromEntries(
    keys.map(key => [key, obj[key]])
  );

const userPreview = pick(user, ['id', 'username']);
console.log(userPreview);

// Omit utility
const omit = (obj, keys) =>
  Object.fromEntries(
    Object.entries(obj).filter(([key]) => !keys.includes(key))
  );

const sanitized = omit(user, ['password']);

Common Variations

Deep Pick
javascript
function deepPick(obj, paths) {
  return paths.reduce((result, path) => {
    const keys = path.split('.');
    let value = obj;
    for (const key of keys) value = value?.[key];
    if (value !== undefined) result[path] = value;
    return result;
  }, {});
}
Pick Defined
javascript
const pickDefined = obj =>
  Object.fromEntries(
    Object.entries(obj).filter(([_, v]) => v !== undefined)
  );

❌ Don't Do This (Outdated Way)

Avoid delete for immutability

javascript
// DON'T DO THIS (mutates original)
delete user.password;

Browser Support

Works in all modern browsers (ES2018+)

#objects#pick#omit