Answer the question
In order to leave comments, you need to log in
How to copy an object in JavaScript?
Good evening gentlemen.
Everyone knows that in JS, an object is passed by reference, not by value. Tell me, what are the options for copying an object?
Answer the question
In order to leave comments, you need to log in
var cloneOfA = JSON.parse(JSON.stringify(a));
or
Why should I google for you?
See also
stackoverflow.com/questions/728360/most-elegant-wa...
Via Object.assign()
const old = {mi: 1, ti: 2} // копируемый объект
const new = Object.asign({}, old);// присваиваем пустому объекту свойства old
new ! == old;// true
how about this option? I'm not sure if it covers all possible options, but the object is copied without saving the reference
const deepClone = (obj) => {
let clone = {};
for (let prop in obj) {
if (typeof obj[prop] === 'object') {
clone[prop] = deepClone(obj[prop]);
} else {
clone[prop] = obj[prop];
}
}
return clone;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question