How to remove a property from a JavaScript object
You can remove a property from an object using the delete
operator:
const o = { field1: 'a', field2: 'b', field3: 'c' };
delete o['field1'];
console.log(o); // logs { field2: 'b', field3: 'c' }
delete o.field2;
console.log(o); // logs { field3: 'c' }
You can also use destructuring, but remember, this operation does not change the original object:
const o = { field1: 'a', field2: 'b', field3: 'c' };
const { field1, ...rest } = o;
console.log(o); // logs {field1: 'a', field2: 'b', field3: 'c' }
console.log(rest); // logs { field2: 'b', field3: 'c' }
You may want to remove the same property from multiple objects. You can do a function for that:
// It returns the object passed as argument without
// the `note` property
const sanitize = ({ notes, ...rest }) => rest;
// The next line returns { id:1 }
sanitize({ notes: 'some note', id: 1 });
// The next line returns { title: "Dune" }
sanitize({ notes: 'Liked it', title: 'Dune' });
If you want to generalize the previous function so that you can select the property to remove, you can do it like the following:
/*
* Remove a property from an object.
* Does not mutate original object.
*
* @param {string} prop - The property to remove.
* @param {Object} - The object to remove the `prop` property.
* @return {Object} The object
*/
const sanitize = (prop, { [prop]: value, ...rest }) => rest;
const o = { field1: 'a', field2: 'b' };
const clean = sanitize('field2', o);
console.log(clean); // logs { field1: "a" }
console.log(o); // logs { field1: 'a', field2: 'b' };
Quite the clever function right? I agree! Although when something feels clever, it tends to be less readable.
Questions
What's the output?
const o = { f1: 1, f2: 2 };
delete o['f1'];
console.log(o);
What's the output?
const o = { a: 'a', b: 'b' };
delete o.a;
console.log(o);
What's the output?
const o = { f: 1, g: 2 };
const { g, ...r } = o;
console.log(o);
What's the output?
const o = { f: 1, g: 2, h: 3 };
const { g, f, ...r } = o;
console.log(r);
What's the output?
const f = ({ a, ...r }) => r;
const o = { a: 1, b: 2 };
console.log(f(o));
What's the output?
const f = (arg1, { [arg1]: v, ...r }) => r;
const res = f('b', { a: 'apple', b: 'banana' });
console.log(res);
What's the output?
const f = (arg1, { [arg1]: v, ...r }) => r;
const obj = { a: 'air', w: 'wind', e: 'earth' };
const res = ['a', 'w'].reduce((a, c) => f(c, a), obj);
console.log(res);