
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.
- The input object has three properties: name, age, and city.
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.
- The input object has a nested object in the details property.
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
Editorial
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. |
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