[Vuejs]-How can I clone data in vuejs?

2πŸ‘

βœ…

If storedata is an Array or Object or Array of object, you can use a library from Lodash.
It will clone your entire storedata to new varibale and any changes in newData won’t affect to storedata.

<script>
import _ from 'lodash'
export default {
  mounted() {
   this.newdata = _.cloneDeep(this.storedata)
  }

}
</script>

1πŸ‘

if storedata is array

 this.newdata = [ ...this.storedata ];

if storedata is json

 this.newdata = { ...this.storedata };

if storedata is string

 this.newdata = this.storedata.slice();

0πŸ‘

For shallow copy [1-level deep] you can use the spread operator like this
this.newdata = [ ...this.storedata ];

If you want to clone a deep nested array then you can use cloneDeep from lodash

yarn add lodash.cloneDeep

and this is how you use it

<script>
import cloneDeep from 'lodash.cloneDeep'
export default {
  mounted() {
   this.newdata = cloneDeep(this.storedata)
  }

}
</script>

Both of the above methods will help you to create a clean array using a new reference

Leave a comment