I have obeject which looks like below which is stored in a seperate file and later imported as import from "path" into the vue component.
const myTemplate =
{
a:{
key11: undefined,
key12: undefined
},
b:{
key21: undefined,
key22: undefined
}
}
Inside the component i am using this myTemplate object to create new data property
<script>
data(){
getfields: myTemplate
}
</script>
In script i loop over the myTemplate and assign it with the prop coming from the parent component which holds the value of the key11, key12 ,key21 ,...so on
Purpose of myTemplate is to act as base/standard format which collect the data from the incoming prop.
Later on getfields is looped over by v-for in <template> tag to display the content
I send props {key11: somevalue1, key12: somevalue2} to my child component matches the keys inside the myTemplate object uses the methods inside this child component to update the same keys in getfields
end result:
{
a:{
key11: somevalue1,
key12: somevalue2
},
b:{
key21: undefined,
key22: undefined
}
}
Problem:
In case of objects, JS copies the references and it alters my myTemplate object as well.
I want to have my myTemplate intact and cannot be altered in any way if the getfields gets changed.
What i've tried:
Deep clone const getfields : JSON.parse(JSON.stringify(myTemplate)) --> dint work for me because
myTemplate is Object of objects
Tried the dynamic import in the hope that would help but it dint
let self= this import("path") .then((data) =>{ self.getfields = data.default })
I suggest you to use Lodash library to clone the object with _.cloneDeep()
E.g:
import _ from 'lodash'
. . .
const getfields = _.cloneDeep(myTemplate)
It's the library I use with Vuejs for preventing those unexpected modifications in the original element because it just clones it.
Official documentation: https://lodash.com/docs/
If you have limited access to internet, you should use VanillaJs to create the clone function, look at this https://medium.com/weekly-webtips/deep-clone-with-vanilla-js-5ef16e0b365c
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With