Tutorialspoint
Problem
Solution
Submissions

Shallow Clone an Object

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 5

Write a JavaScript function to create a shallow clone of a given object. A shallow clone creates a new object with the same top-level properties, but nested objects are still referenced (not deeply copied). The function should return a new object that is independent at the first level.

Example 1
  • Input: obj = {name: "Alice", age: 30, city: "New York"}
  • Output: {name: "Alice", age: 30, city: "New York"}
  • Explanation:
    • The input object has three properties: name, age, and city.
    • A new object is created with the same property-value pairs.
    • Modifying the cloned object's properties won't affect the original.
    • Both objects have the same values but are different object references.
    • The shallow clone is successfully created.
Example 2
  • Input: obj = {user: "Bob", details: {email: "bob@example.com", phone: "123-456"}}
  • Output: {user: "Bob", details: {email: "bob@example.com", phone: "123-456"}}
  • Explanation:
    • The input object has a nested object in the details property.
    • The shallow clone copies the reference to the details object.
    • The cloned object has the same structure as the original.
    • Changes to nested properties will affect both objects (shallow behavior).
    • The top-level properties are independent between original and clone.
Constraints
  • The input will always be a valid object
  • Handle primitive values, arrays, and nested objects
  • Only create shallow copies, not deep copies
  • Time Complexity: O(n) where n is the number of properties
  • Space Complexity: O(n) for the new object
Control StructuresPwCKPMG
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use Object.assign() method to copy properties
  • Alternative: use spread operator (...) for modern JavaScript
  • Iterate through object properties using for...in loop
  • Copy each property value to the new object
  • Remember that nested objects will share references
  • Consider using Object.keys() with reduce method

Steps to solve by this approach:

 Step 1: Create a new empty object as the target for cloning.
 Step 2: Use Object.assign() method with empty object as first parameter.
 Step 3: Pass the source object as second parameter to Object.assign().
 Step 4: Object.assign() copies all enumerable properties from source to target.
 Step 5: Return the new object which contains copied properties.
 Step 6: The result is a shallow clone where top-level properties are independent.
 Step 7: Nested objects still share references between original and clone.

Submitted Code :