Shallow copy an object
Copy own enumerable properties into a new object.
function shallowCopy(object) { return { ...object }; }
Input & expected output
Input
{
"to": "[email protected]",
"data": {
"name": "Ana"
}
}Expected output
{
"to": "[email protected]",
"data": {
"name": "Ana"
}
}The edge case
Input
{}Expected output
{}Know the limits
- Nested objects are shared, not copied. Use structuredClone for a deep copy.
- The original second variant, obj => {...obj}, is a block, not an object literal; it needs parentheses.
The function above is the implementation used by the lab. The lab validates JSON types and caps size before execution; include equivalent validation when accepting untrusted input in your application.
Source & maintenance
Based on Shallow copy an object from the original 1loc collection by Nguyen Huu Phuoc, with Namysh. Copyright (c) 2020 phuoc-ng. MIT licensed.
Uses object spread; the original arrow variant obj => {...obj} was a syntax error. Original MDX retained as inert source evidence.
Maintained by Oveyon. Source commit: 14b481cf60df. Read the license.
Keep exploring
- Pick properties from an object — Build a new object with only the requested own properties.
- Omit properties from an object — Keep the own enumerable fields that are not in a supplied list.
- Create an object from pairs of key and value — Turn [key, value] pairs into a plain object with Object.fromEntries.