K
K
keslo2015-10-31 23:10:32
JavaScript
keslo, 2015-10-31 23:10:32

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

3 answer(s)
S
sanex3339, 2015-10-31
@keslo

var cloneOfA = JSON.parse(JSON.stringify(a));
or
Why should I google for you?
See also
stackoverflow.com/questions/728360/most-elegant-wa...

M
mikhailrojo, 2016-11-27
@mikhailrojo

Via Object.assign()

const old = {mi: 1, ti: 2} // копируемый объект
const new = Object.asign({}, old);// присваиваем пустому объекту свойства old
new ! == old;// true

V
vit134, 2018-06-04
@vit134

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 question

Ask a Question

731 491 924 answers to any question