Photo by PJH on Unsplash

On this page

This chapter follows Defining object properties in JavaScript.

You have a record of nested objects and need a shallow copy without one key—or only a subset of keys. Rest destructuring and Object.fromEntries keep the source object intact.

Drop one key with rest destructuring

const data = {
item1: { key: 'a', value: 'b' },
item2: { key: 'c', value: 'd' },
item3: { key: 'e', value: 'f' },
};
const { item2, ...newData } = data;

When the key name is in a variable:

const key = 'item2';
const { [key]: _removed, ...newData } = data;

The _removed binding holds the omitted value; only newData is returned to callers.

Allowlist with Object.fromEntries

For several allowed keys, filter entries then rebuild the object:

const raw = {
item1: { key: 'a' },
item2: { key: 'b' },
item3: { key: 'c' },
};
const allowed = ['item1', 'item3'];
const filtered = Object.fromEntries(
Object.entries(raw).filter(([key]) => allowed.includes(key)),
);

This is a shallow copy: nested objects are shared with raw. For denylists, invert the predicate: !denied.includes(key).

Small utility

function pick(obj, keys) {
const set = new Set(keys);
return Object.fromEntries(
Object.entries(obj).filter(([k]) => set.has(k)),
);
}
function omit(obj, key) {
const { [key]: _, ...rest } = obj;
return rest;
}

Prefer pick/omit at module boundaries so API shapes stay explicit in TypeScript.

Next: Prototypes and inheritance.

Search articles

Type a word to search published articles.

Open the search page