How many ways to copy object in javasript and jquery
Loading
How many ways to copy object in javasript and jquery
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sangeetha SRank #212 · 11.4K reputationPosted Feb 11, 2025, 1:26 AM EST
In JavaScript and jQuery, there are several ways to copy objects. Here are some common methods:
JavaScript
-
JavaScript
-
JavaScript
-
JavaScript
jQueryUsing Object.assign():
const original = { a: 1, b: 2 }; const copy = Object.assign({}, original);Using the Spread Operator:
const original = { a: 1, b: 2 }; const copy = { ...original };Using JSON methods (for deep copy, but only for JSON-compatible objects):
const original = { a: 1, b: { c: 2 } }; const copy = JSON.parse(JSON.stringify(original));Using jQuery's $.extend():
const original = { a: 1, b: 2 }; const copy = $.extend({}, original);Deep copy with $.extend():
const original = { a: 1, b: { c: 2 } }; const copy = $.extend(true, {}, original);Jignesh KumarRank #91 · 22.9K reputationPosted Feb 24, 2025, 1:52 AM EST
Hi Dashrath,
We can use below methods,
structuredClone()(latest)_.cloneDeep()(best library)$.extend(true, ...)(if using jQuery){ ...obj }Object.assign()chasetony20 reputationPosted Feb 27, 2025, 1:13 AM EST
Shallow Copy Methods:
Object.assign()const copied = Object.assign({}, original);Copies enumerable own properties from source objects to a target object. Doesn't copy prototype chain or nested objects.
Spread Operator
const copied = { ...original };Modern syntax for shallow cloning, equivalent to
Object.assign().Array.prototype.slice()
const copiedArray = originalArray.slice();Array-specific shallow copy method.
Array.prototype.concat()
const copiedArray = [].concat(originalArray);Alternative array shallow copy method.
Manual Property Copy
const copied = {}; for (const key in original) { if (original.hasOwnProperty(key)) { copied[key] = original[key]; } }Deep Copy Methods:
JSON.parse(JSON.stringify())const deepCopied = JSON.parse(JSON.stringify(original));Serialization-based approach. Loses:
undefinedSymbolpropertiesDate,RegExpstructuredClone()const deepCopied = structuredClone(original);Native method (ES2022+) that handles:
Date,RegExp,Map,Set, etc.Lodash
_.cloneDeep()const deepCopied = _.cloneDeep(original);Library implementation with comprehensive type handling.
Recursive Copy Function
function deepClone(obj, hash = new WeakMap()) { if (obj === null || typeof obj !== 'object') return obj; if (hash.has(obj)) return hash.get(obj); let clone = new obj.constructor(); hash.set(obj, clone); for (const key in obj) { if (obj.hasOwnProperty(key)) { clone[key] = deepClone(obj[key], hash); } } return clone; }