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

推荐订阅源

WordPress大学
WordPress大学
Forbes - Security
Forbes - Security
C
CERT Recently Published Vulnerability Notes
The Last Watchdog
The Last Watchdog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
S
Secure Thoughts
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
T
Troy Hunt's Blog
N
News | PayPal Newsroom
人人都是产品经理
人人都是产品经理
S
Securelist
J
Java Code Geeks
月光博客
月光博客
博客园 - 叶小钗
云风的 BLOG
云风的 BLOG
Hugging Face - Blog
Hugging Face - Blog
T
Threatpost
H
Hacker News: Front Page
Recent Commits to openclaw:main
Recent Commits to openclaw:main
小众软件
小众软件
大猫的无限游戏
大猫的无限游戏
PCI Perspectives
PCI Perspectives
T
The Blog of Author Tim Ferriss
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
Google DeepMind News
Google DeepMind News
量子位
SecWiki News
SecWiki News
有赞技术团队
有赞技术团队
TaoSecurity Blog
TaoSecurity Blog
N
Netflix TechBlog - Medium
Latest news
Latest news
博客园_首页
L
LINUX DO - 最新话题
V
Visual Studio Blog
G
Google Developers Blog
P
Palo Alto Networks Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
T
Tenable Blog
Simon Willison's Weblog
Simon Willison's Weblog
Scott Helme
Scott Helme
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
P
Privacy International News Feed
Recorded Future
Recorded Future
Stack Overflow Blog
Stack Overflow Blog
O
OpenAI News
T
Tor Project blog
IT之家
IT之家
S
SegmentFault 最新的问题

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() 2 Ways to Remove a Property from an Object in JavaScript '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? 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
3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses)
Dmitri Pavlutin · 2020-07-28 · via Dmitri Pavlutin Blog

In this post, you'll find 3 easy ways to perform shallow clone (aka copy) of objects in JavaScript.

As a bonus, I'm going to show how you can also update, add, or remove properties in place on the clone. That's useful when you want to perform an update on the object in an immutable manner.

Note

The 3 ways to clone objects described in this post perform shallow copy.

A shallow copy means that only the actual object gets copied. If the copied object contains nested objects — these nested objects aren't get cloned.

Table of Contents

    • Note
  • 1. Cloning using object spread
    • 1.1 Object spread bonus: add or update cloned props
  • 2. Cloning using object rest
    • 2.1 Object rest bonus: skip cloned props
    • 2.2 Super bonus: combining object spread and rest
  • 3. Cloning using Object.assign()
    • 3.1 Object.assign() bonus: add or update cloned props
  • 4. Summary

1. Cloning using object spread

The simplest way to clone a plain JavaScript object is to invoke the object spread operator:


const clone = {

...object

};


Where object is the object you'd like to copy, and clone is the shallow copy of object.

For example, let's create a shallow copy of hero object:


const hero = {

name: 'Batman',

city: 'Gotham'

};

const heroClone = {

...hero

};

heroClone; // { name: 'Batman', city: 'Gotham' }

hero === heroClone; // => false


heroClone is a clone object of hero, meaning that it contains all the properties of hero.

hero === heroClone evalutes to falsehero and heroClone are, nevertheless, difference object instances.

1.1 Object spread bonus: add or update cloned props

An immediate benefit of using object spread is that you can update or add new properties to the cloned object in place if you need it.

Let's clone the hero object, but update name property to a different value and add a new property realName:


const hero = {

name: 'Batman',

city: 'Gotham'

};

const heroEnhancedClone = {

...hero,

name: 'Batman Clone',

realName: 'Bruce Wayne'

};

heroEnhancedClone;

// { name: 'Batman Clone', city: 'Gotham', realName: 'Bruce Wayne' }


2. Cloning using object rest

Another good way to shallow clone objects is by using the object rest operator:


const { ...clone } = object;


Again, let's use the rest operator to make a copy of hero object:


const hero = {

name: 'Batman',

city: 'Gotham'

};

const { ...heroClone } = hero;

heroClone; // { name: 'Batman', city: 'Gotham' }

hero === heroClone; // => false


After applying the rest operator const { ...heroClone } = hero, the heroClone variable contains a copy of hero object.

2.1 Object rest bonus: skip cloned props

A nice bonus when using object rest is the ability to skip certain properties when cloning.

For example, let's create a clone of hero object, but skip city property in the clone:


const hero = {

name: 'Batman',

city: 'Gotham'

};

const { city, ...heroClone } = hero;

heroClone; // { name: 'Batman' }


2.2 Super bonus: combining object spread and rest

Object spread brings the bonus of updating or adding new properties, while object rest has the benefit of skipping properties in the resulting clone.

Can you combine object spread and rest into one statement to inherit all these benefits? Yes, you can!

Let's clone the hero object, also adding a new property realName and skipping the property city:


const hero = {

name: 'Batman',

city: 'Gotham'

};

const { city, ...heroClone } = {

...hero,

realName: 'Bruce Wayne'

};

heroClone; // { name: 'Batman', realName: 'Bruce Wayne' }


Combining the object spread and rest to clone objects and perform properties manipulation in a single statement is great!

3. Cloning using Object.assign()

Finally, Object.assign(target, ...sources) let's you peform the same object clone:


const clone = Object.assign({}, object);


Let's use Object.assign() in practice and create a clone object of hero object:


const hero = {

name: 'Batman',

city: 'Gotham'

};

const heroClone = Object.assign({}, hero);

heroClone; // { name: 'Batman', city: 'Gotham' }

hero === heroClone; // => false


Object.assign({}, hero) creates a clone of hero object by merging the second argument hero into the first argument {}.

3.1 Object.assign() bonus: add or update cloned props

Object.assign() enables also to update or add new properties to the clone.

Let's copy the hero object, but at the same time update name property:


const hero = {

name: 'Batman',

city: 'Gotham'

};

const heroClone = Object.assign({}, hero, { name: 'Batman Clone' });

heroClone; // { name: 'Batman Clone', city: 'Gotham' }


Object.assign({}, hero, { name: 'Batman Clone' }) creates the object in 2 steps.

First, the second argument hero is merged into the first argument {}. This equals to { name: 'Batman', city: 'Gotham' }.

Second, the third argument { name: 'Batman Clone' } is merged into the result from the previous step, overwriting the property name. Finally, you get the object { name: 'Batman Clone', city: 'Gotham' }.

4. Summary

JavaScript provides 3 good ways to clone objects: using spread operator, rest operator and Object.assign() function.

Aside from just cloning objects, using object spread and Object.assign() lets you add or updated properties when creating the clone.

Rest operator also gives the benefit of skipping certain properties when cloning.

And what's great, you can combine the object spread and rest in a single statement, so you can clone the object, and at the same time add, update or skip properties from being cloned.

That's useful if you'd like to embrace the immutability and be able to manipulate the cloned object's properties in place.

What other good ways to clone objects in JavaScript do you know?