0

I am making copy of vuex state. That array structure is like this:

export const store = new Vuex.Store({
  state: {
    contacts: [
      {
        id: 122345,
        name: "Marko Marki",
        email: "marko@marko.com",
        phones: ["478 8273", "787 7671"],
        avatar: "https://avatars0.githubusercontent.com/u/9064066?v=4&s=460"
      },
      {
        id: 122346,
        name: "Ivan Ivandi",
        email: "ivan@ivan.com",
        phones: ["787 7671"],
        avatar: "https://avatars0.githubusercontent.com/u/9064066?v=4&s=460"
      },

I am making copy of this state to pass it to my edit component to work with like this:

getContactsCopy(state) {
      const copyContacts = state.contacts.map(contact => ({...contact}))
      console.log(copyContacts)
      return copyContacts
    }

...and back in my edit component I am getting this copyContacts data as expected, but for phone numbers in phones array I still have reference to original state which is not what I want, for all other properties like name, email and so on I have copy and on canceling the edit mode original state stays as it was except phone numbers. How can I make copy of my every object property including that phones array?

Pokreniseweb
  • 165
  • 3
  • 16
  • 1
    Possible duplicate of [How to Deep clone in javascript](https://stackoverflow.com/questions/4459928/how-to-deep-clone-in-javascript) – Constantin Groß Oct 28 '19 at 17:47
  • Sorry if I duplicate, but duplicate you reference at is 8 years old – Pokreniseweb Oct 28 '19 at 17:49
  • 1
    @Pokreniseweb That's pretty irrelevant for something as basic as this. At the end of the day, Vue is still just Javascript and the core principles are the same. – Etheryte Oct 28 '19 at 17:51
  • I understand that, but I need fresh and modern solution, and best practise used for cases like mine problem with vue – Pokreniseweb Oct 28 '19 at 17:53
  • 1
    There is no built-in way in ES6, [see here](https://stackoverflow.com/questions/38416020/deep-copy-in-es6-using-the-spread-syntax). If you want a "fresh and modern" solution, you could just as well rename the function from the referenced answer to `shinyNewModernClone2019()`... ;-) It would still work the same (and by the way it was even refined over the years). You can also take a look at how [lodash's `baseClone`](https://github.com/lodash/lodash/blob/master/.internal/baseClone.js) does it (and [`cloneDeep`](https://github.com/lodash/lodash/blob/master/cloneDeep.js) for recursiveness). – Constantin Groß Oct 28 '19 at 18:09
  • @Constantin Lodash saves the day :) – Pokreniseweb Oct 28 '19 at 18:44

0 Answers0