惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
雷峰网
雷峰网
The Register - Security
The Register - Security
The Cloudflare Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
I
InfoQ
博客园 - 三生石上(FineUI控件)
H
Help Net Security
博客园 - 司徒正美
Vercel News
Vercel News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
B
Blog
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
L
LangChain Blog
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recorded Future
Recorded Future
小众软件
小众软件
Martin Fowler
Martin Fowler
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
V
Visual Studio Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
V
V2EX
Blog — PlanetScale
Blog — PlanetScale

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
2 Ways to Remove a Property from an Object in JavaScript
Dmitri Pavlutin · 2021-08-17 · via Dmitri Pavlutin Blog

A JavaScript object is a collection of properties, where each property has a name and a value.


const employee = {

name: 'John Smith',

position: 'Sales Manager',

};


The user variable contains an object describing an employee. The object contains 2 properties that describe employee data: name and position.

Sometimes, however, you need to remove properties from an object. For example, how would you remove the position property from the employee object?

Let's see 2 common ways on how to remove properties from an object in JavaScript — using the delete operator (mutable way) and object destructuring combined with object rest (immutable way).

1. delete operator

delete is a special operator in JavaScript that removes a property from an object. Its single operand usually accepts a property accessor to indicate what property to remove:

A) Remove using a dot property accessor:

B) Remove using square brakets property accessor:


delete object['property'];

// or

const name = 'dynamicProperty';

delete object[name];


When applying the delete operator on a property accessor, the operator removes the corresponding property from the object:


const employee = {

name: 'John Smith',

position: 'Sales Manager'

};

delete employee.position;

console.log(employee); // { name: 'John Smith' }


Open the demo.

Initially, employee has 2 properties: name and position.

But after applying the delete operator on the position property: delete employee.position, the property is removed from the object. Simple as that.

The property removal using delete operator is mutable because it mutates (aka alters, modifies) the original object.

In case if the property name to remove is determined dynamically, then you can use the square brackets syntax:


const employee = {

name: 'John Smith',

position: 'Sales Manager'

};

const name = 'position';

delete employee[name];

console.log(employee); // { name: 'John Smith' }


Open the demo.

delete employee[name] removes the property which name is contained inside name variable.

2. Object destructuring with rest syntax

Another approach to removing properties, but in an immutable manner without altering the original object, is to use the object destructuring and rest syntax.

The idea is simple: destructure the object to the property you want to remove, and the remaining properties collect into a rest object:

A) The property name is known:


const { property, ...restObject } = object;


B) The property name is dynamic:


const propNameToRemove = 'property';

const { [propNameToRemove]: removedProperty, ...restObject } = object;


After applying the destructuring and rest syntax, restObject is going to contain the same properties as object, only without the removed property.

For example, let's remove the property position from employee object:


const employee = {

name: 'John Smith',

position: 'Sales Manager'

};

const { position, ...employeeRest } = employee;

console.log(employeeRest); // { name: 'John Smith' }

console.log(employee);

// { name: 'John Smith',position: 'Sales Manager' }


Open the demo.

The statement const { position, ...employeeRest } = employee destructures the employee objects and collects the properties into a rest object employeeRest without including the position property.

Object destructuring with rest syntax is an immutable way of property removal: the original employee object isn't mutated. Rather a new object employeeRest is created which contains all the properties of employee but without the removed position.

If the property name to remove is determined dynamically, then you can use the dynamic property name destructuring syntax:


const employee = {

name: 'John Smith',

position: 'Sales Manager'

};

const propNameToRemove = 'position';

const { [propNameToRemove]: removedProperty, ...employeeRest } = employee;

console.log(employeeRest); // { name: 'John Smith' }


Open the demo.

const { [propNameToRemove]: removedProperty, ...employeeRest } = employee let's you remove a property with dynamic property name by collecting the properties, but removed one, into employeeRest object.

What's interesting is that you can remove multiple properties at once using the destructuring and rest syntax:


const employee = {

name: 'John Smith',

position: 'Sales Manager',

experience: 6, // years

};

const { position, experience, ...employeeRest } = employee;

console.log(employeeRest); // { name: 'John Smith' }


Open the demo.

const { position, experience, ...employeeRest } = employee has removed 2 properties at once: position and experience.

3. Conclusion

In JavaScript, there are 2 common ways to remove properties from an object.

The first mutable approach is to use the delete object.property operator.

The second approach, which is immutable since it doesn't modify the original object, is to invoke the object destructuring and spread syntax: const {property, ...rest} = object.

Side challenge: what is the time complexity of the property removal using delete and object rest syntax? Write your opinion in a comment below!