Shallow And Deep Copy
Part of the Logic & Flow section of Coddy's JavaScript journey — lesson 25 of 65.
When copying objects, we have two types of copies:
- Shallow Copy - copies only the first level
- Deep Copy - copies all nested levels
Shallow Copy Methods:
Using spread operator:
const original = { a: 1, b: { x: 2 } };
const spreadCopy = { ...original };Using Object.assign() which creates a new object by copying properties from source to target object:
const assignCopy = Object.assign({}, original);Problem with Shallow Copy:
original.b.x = 3;
console.log(spreadCopy.b.x); // 3
// (nested objects share reference)
console.log(assignCopy.b.x); // 3Understanding JSON Methods & Deep Copy
JSON.stringify() converts a JavaScript object into a JSON string:
const obj = { name: "John", age: 30 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // "{"name":"John","age":30}"JSON.parse() converts a JSON string back into a JavaScript object:
const backToObject = JSON.parse(jsonString);
console.log(backToObject); // { name: "John", age: 30 }Deep Copy using JSON:
const original = { a: 1, b: { x: 2 } };
const deepCopy = JSON.parse(JSON.stringify(original));
original.b.x = 3;
console.log(deepCopy.b.x); // 2 (completely independent)Challenge
EasyCreate a function named processCart that takes a JSON string representing a shopping cart. The cart contains an array of products with names and prices. Your task is to:
- Parse the JSON string into a JavaScript object
- Create TWO separate carts from it
- In the second cart:
- Add a
discountedproperty to each item set to false - Apply a 10% discount to all items that have
pricegreater than 50 - Set 'discounted' to true for items that received the discount
- Add a
- Return an array containing both carts
Cheat sheet
When copying objects, we have two types of copies:
- Shallow Copy - copies only the first level
- Deep Copy - copies all nested levels
Shallow Copy Methods:
Using spread operator:
const original = { a: 1, b: { x: 2 } };
const spreadCopy = { ...original };Using Object.assign():
const assignCopy = Object.assign({}, original);Problem with Shallow Copy:
original.b.x = 3;
console.log(spreadCopy.b.x); // 3 (nested objects share reference)JSON Methods:
JSON.stringify() converts JavaScript object to JSON string:
const obj = { name: "John", age: 30 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // "{"name":"John","age":30}"JSON.parse() converts JSON string back to JavaScript object:
const backToObject = JSON.parse(jsonString);
console.log(backToObject); // { name: "John", age: 30 }Deep Copy using JSON:
const original = { a: 1, b: { x: 2 } };
const deepCopy = JSON.parse(JSON.stringify(original));
original.b.x = 3;
console.log(deepCopy.b.x); // 2 (completely independent)Try it yourself
function processCart(jsonString) {
// Write code here
}
// Don't write anything outside the functionThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String FundamentalsIterate Over StringsTemplate LiteralsString MethodsRecap - String Weaver4JSON Part 2
Iterate Over JSONNested JSONJSON Optional ChainingShallow And Deep CopyRecap - Bicycle ShopRecap - Solar System10Manage Festival System
Project OverviewAdd Movies & Venues2Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays5Sets Part 1
What Is A Set?Iterating Over SetsAdding An ElementRemoving An ElementChecking If An Element ExistsSize And Is EmptyCopy And ClearRecap - Basic Of Sets8Arrays Interesting Topics
Array DestructuringSpread Syntax in ArraysSparse ArraysRecap - Arrays Workshop3JSON Part 1
What is a JSON?Check If Key ExistsObject MethodsThe Spread Operator Part 1The Spread Operator Part 2Remove KeysRecap - JSON Manipulate Keys