0

I have an obj1:

const obj1 = { val: {v: 0}}

I'm trying to deep copy it by doing:

const obj2 = {...obj1}

However the {v: 0} is still not copied, how would I do this>

marc2019
  • 47
  • 5

4 Answers4

0

I guess this is the easiest way, but a bit clumsy

const obj2 = JSON.parse(JSON.stringify(obj1))

Otherwise you need to write a recursive cloning function or use some library - just search for cloneDeep, copyDeep or smth along these lines.

  • This is really just the old school way (with far more risk) of doing `const obj2 = { ...obj1 }` Doing `JSON.stringify` will modify your object in a lot of ways that you may not want it to (ie loss of functions, data type conversions etc...) – mwilson Apr 02 '21 at 20:56
  • @mwilson, `const obj2 = { ...obj1 }` doesn't do deep copy, only shallow (top level props). Yes, you're right on functions etc, but in many cases you just need to clone POJOs. – Viktor Molokostov Apr 02 '21 at 21:59
0

You can use lodash-es package for this. It provides the function cloneDeep() that will recursively clone values.

Here is the package: https://www.npmjs.com/package/lodash-es

Here are the Docs: https://lodash.com/docs/4.17.15#cloneDeep

import { cloneDeep as _cloneDeep } from 'lodash-es';

const obj2  = _cloneDeep(obj1);

NeNaD
  • 18,172
  • 8
  • 47
  • 89
  • Bring in an entire library just to clone one object? – mwilson Apr 02 '21 at 20:58
  • No, when using `lodash-es` only what you import will be included in final bundle. If you import just `cloneDeep`, only that one will be included in final bunde, and not the whole package. – NeNaD Apr 02 '21 at 21:25
0

You are doing it how you should (with the spread operator). The spread operator will copy everything just fine.

const obj1 = { val: {v: 0} };
const obj2 = { ...obj1 };
console.log(obj2);

const obj1 = {
  test: 1,
  test2: {
    t: 1,
    f: () => console.log('hello')
  }
};
const obj2 = { ...obj1 };
console.log( obj2 );
console.log( obj2.test2.f() );

If you were to (at any time) do a JSON.stringify on the object, you will lost any methods/functions or other things that don't translate to the json scheme so it's best to avoid doing that. Object destructuring is what you want.

mwilson
  • 12,295
  • 7
  • 55
  • 95
-1

I don't have enough rep to even flag but this is a cleeeeeear duplicate of a lot of questions

even googling the title would have been easier for you

anyway I use a module called rfdc that does just that, and lodash has a function to do it to otherwise you can loop through your src object with a recursive function that adds fields to your dest object

skpn
  • 89
  • 1
  • 5