0

I know that TypeScript passes objects by reference and that there is no clear best practice to go around it to get a deep copy, but i find it difficult to work with this, especially when working in a theme.

I just had the case with a component that has an array of object and passes those to child components. Each child component updates the single object passed as input. Problem: I wasn't the one who programmed it so i had no idea that the child component modified the values directly. And even if i was, i'm pretty sure i wouldn't have remembered six months later.

Is there a clear best practice to deal with this?

Magnesium
  • 597
  • 6
  • 22
  • Often, it's enough to use `const copiedArr = JSON.parse(JSON.stringify(oldArr))`. That way you're sure that you won't be updating anything on the original array (or object). There are some specific things that might not be copied using this technique, but for simple data it works fine. Learn more here: https://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-deep-clone-an-object-in-javascript – Michael Beeson Oct 16 '19 at 13:28
  • It's not always simple datas, otherwise i would not have bothered the community with the question. I pass object models. And for example, a Person object might have a getFullName() method that returns that concatenates the first name and last name. – Magnesium Oct 16 '19 at 13:32

1 Answers1

2

If lodash is in your toolbelt, you can use _.cloneDeep(). I've used this reliably with relatively large objects and large collections without any issues.

https://lodash.com/docs/4.17.15#cloneDeep

var objects = [componentObj1, componentObj2];
var deep = _.cloneDeep(objects);
console.log(deep[0] === objects[0]);
// => false
Damian C
  • 2,111
  • 2
  • 15
  • 17
  • I've heard about it, how reliable and following good practices is it? Thanks for the suggestion. – Magnesium Oct 16 '19 at 13:34
  • 1
    Since good practices and reliability can be blurred with opinions. I'll try to give facts. You'll find that lodash utilizes native methods to work with collections. Its basically a wrapper that gives you a lot of shortcuts to tools that are native to JavaScript. I use it all the time. – Damian C Oct 16 '19 at 13:36
  • I'll try it out. The problem i have with adding external libraries is that i work for a big company and our softwares tend to end being supported for over ten years. But when you have to, you have to i guess ;) – Magnesium Oct 16 '19 at 15:08