0

I want save a original array and modify the copy using a form (in a children vue component). But when the copy is modified, the origin is modified too.

I have tried:

this.updatedDatas = [...this.initialList]
this.updatedDatas = this.initialList.map((x)=> x)
this.updatedDatas = Array.from(this.initialList)

Parent script:

this.initialList = [{name: 'John'}, {name: 'Isa'}]
this.updatedDatas = [...this.initialList]

Parent template:

<form-child :item="updatedDatas[1]" />

Child template:

<textarea v-model="item.name"></textarea>

Child script:

this.$emit('updated', this.item)
1
  • I continue having the problem with a nested object. Any other solution? Commented May 23, 2019 at 19:13

1 Answer 1

1

you need to do a deep copy of your array, otherwise you're just ending up with two arrays, that have the same object references. A deep copy will re-create the internals of the objects and arrays within.

You can use a package line lodash or build your own.

An external library will give you "infinite" depth, but this will give you 2 levels which may be enough for you.

this.updatedDatas = this.initialList.map(i => ({...i});

additional resources for deep copying

https://www.npmjs.com/package/clone

http://www.greywyvern.com/?post=363

Sign up to request clarification or add additional context in comments.

2 Comments

can also use this.updatedData = JSON.parse(JSON.stringify(this.initialList))
Yes, though I don't like recommending JSON.stringify because it may lead to errors like Uncaught TypeError: Converting circular structure to JSON. The clone libraries tend to handle that better.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.