Remove a key from an object immutably in JavaScript
Beginner · 3 min read
Sometimes an object carries a field you don't want to pass on. A user record has a password hash you must not send to the browser. A form has a helper field the server doesn't expect. You need the same object, minus one key.
In this tutorial you will remove rollno from a student object in two ways: by changing the object, and by making a copy without it. Along the way you will see why setting a key to undefined is not the same as removing it. You need to know how to write an object and read a property.
Changing an object, or copying it
There are two kinds of fix. A mutating fix changes the object you already have. Anyone else holding that object sees the change too. An immutable fix leaves the original alone and gives you a new object. Immutable code is easier to follow, because a value never changes behind your back.
Destructuring in one minute
Destructuring pulls values out of an object into variables, by key name:
const { name } = { name: 'Ada', age: 36 };
console.log(name); // Ada
Add ...rest at the end, and everything you didn't name goes into a new object called rest:
const { age, ...others } = { name: 'Ada', age: 36, city: 'Lagos' };
console.log(others); // { name: 'Ada', city: 'Lagos' }
That is the whole trick for the immutable version.
Here is the exercise. Try it yourself first, or follow along as we build it.
2 Delete a property
easyRemove rollno from the student object, showing the object before and after. Then do it without modifying the original.
Stuck? Three hints, smallest first
- 1.
delete obj.keyremoves the property, and it returnstrueon success. - 2. Setting a property to
undefinedis not the same as deleting it: the key remains. - 3. Rest destructuring gives you a copy with the key left out and the original untouched.
Step 1: look at the object first
JSON.stringify turns an object into text, which is a handy way to print it on one line:
const student = { name: 'David Rayy', sclass: 'VI', rollno: 12 };
console.log(JSON.stringify(student)); // {"name":"David Rayy","sclass":"VI","rollno":12}
Step 2: make a copy without rollno
Name rollno in the destructuring, and gather the rest:
const { rollno, ...withoutRollno } = student;
console.log(JSON.stringify(withoutRollno)); // {"name":"David Rayy","sclass":"VI"}
console.log(rollno); // 12
console.log(JSON.stringify(student)); // {"name":"David Rayy","sclass":"VI","rollno":12}
Three things happened in one line. rollno became its own variable holding 12. withoutRollno is a new object with the other two keys. And student still has all three keys, untouched.
Step 3: the tempting wrong turn
You might think "just set it to undefined". Try it on a copy:
const blanked = { ...student, rollno: undefined };
console.log(JSON.stringify(blanked)); // {"name":"David Rayy","sclass":"VI"}
console.log(Object.keys(blanked)); // [ 'name', 'sclass', 'rollno' ]
The JSON looks right, because JSON.stringify skips keys whose value is undefined. But Object.keys shows the key is still there, holding nothing. The in operator, which asks "does this key exist?", agrees:
console.log('rollno' in blanked); // true
console.log('rollno' in withoutRollno); // false
So two objects can print the same JSON and still be different. Code that counts keys or loops over them will see the extra one.
Step 4: really remove it with delete
The question also asks for the mutating version. The delete operator removes a key from the object itself:
const removed = delete student.rollno;
console.log(JSON.stringify(student)); // {"name":"David Rayy","sclass":"VI"}
console.log(removed); // true
console.log(Object.hasOwn(student, 'rollno')); // false
console.log(student.rollno); // undefined
delete returns true when it worked. Object.hasOwn confirms the key is gone, and reading it now gives undefined. Unlike Step 3, there is no key left behind.
One odd detail: deleting a key that was never there also returns true.
console.log(delete student.nothing); // true
So the return value tells you the key is not there afterwards, not that something was removed.
The full solution
The panel prints the student, makes the copy without rollno, shows the undefined trap, and finally deletes the key from the original. Press Run to see each line.
const student = { name: 'David Rayy', sclass: 'VI', rollno: 12 };
console.log('before:', JSON.stringify(student));
// Non-destructive: pull the key out into its own variable and keep the rest.
const { rollno, ...withoutRollno } = student;
console.log('copy without rollno:', JSON.stringify(withoutRollno));
console.log('original still intact:', JSON.stringify(student));
// The difference between deleting and blanking.
const blanked = { ...student, rollno: undefined };
console.log('set to undefined:', JSON.stringify(blanked), '<- JSON drops it...');
console.log('...but the key is still there:', Object.keys(blanked));
// Destructive, as the question asks.
const removed = delete student.rollno;
console.log('after delete:', JSON.stringify(student), ' delete returned', removed);
Output
11 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 11 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the copy has the key removed', Object.keys(withoutRollno), ['name', 'sclass']);
test('the extracted value is available', rollno, 12);
test('delete reports success', removed, true);
test('the key is gone from the original', Object.hasOwn(student, 'rollno'), false);
test('reading it now gives undefined', student.rollno, undefined);
test('the other properties survive', student, { name: 'David Rayy', sclass: 'VI' });
test('deleting something absent also returns true', delete student.nothing, true);
test('setting to undefined KEEPS the key', Object.hasOwn(blanked, 'rollno'), true);
test('so the key count differs', Object.keys(blanked).length - Object.keys(withoutRollno).length, 1);
test('though JSON hides the difference', JSON.stringify(blanked), JSON.stringify(withoutRollno));
test('"in" still finds a key set to undefined', 'rollno' in blanked, true);
Two ways to make a property go away, and they are not equivalent. delete removes the key; assigning undefined leaves the key present with an empty value. The assertions show the trap clearly: JSON.stringify produces identical output for both, so serialising the two objects makes them look the same while Object.keys and in still tell them apart. Prefer the rest-destructuring form when you can — it leaves the input alone, and code that does not mutate its inputs is easier to reason about.
Common mistakes
- Setting the key to
undefinedand calling it removed. The key stays.Object.keys,inand loops still find it. - Trusting
JSON.stringifyto compare. It hides keys that holdundefined, so a blanked object and a cleaned one print the same. - Using
deleteon an object other code shares. Everyone holding that object loses the key. Prefer the rest-destructuring copy.
Try it yourself
- Remove two keys at once,
sclassandrollno, with a single destructuring line. - Write
omit(obj, key)that returns a copy withoutkey. (Hint:const { [key]: _, ...rest } = obj.) - Print
Object.keys(blanked).lengthandObject.keys(withoutRollno).length. Explain the difference.