I have a JavaScript object in a Vue instance that is being deep copied into another JavaScript object via a computed property. However for some reason it shallow copies the object in question instead of a deep copy, even though JSON.parse(JSON.stringify())
is being used:
<div id="app">
<v-app id="inspire">
<v-row>
<v-col cols="6">
<v-text-field
v-model="formDialog.inputs.definition.val"
placeholder="Definition from FormDialog"></v-text-field>
</v-col>
<v-col cols="6">
<v-text-field
v-model="initFields.definition"
placeholder="Definition from Init Fields"></v-text-field>
</v-col>
</v-row>
<v-row>
<v-col cols="6">
<v-text-field
v-model="formDialog.inputs.synonym.val"
placeholder="Synonym from FormDialog"></v-text-field>
</v-col>
<v-col cols="6">
<v-text-field
v-model="initFields.synonym"
placeholder="Synonym from Init Fields"></v-text-field>
</v-col>
</v-row>
</v-app>
</div>
I am attempting to deep copy the value of formDialog.inputs
using the following loop within a compupted property:
new Vue({
el: '#app',
vuetify: new Vuetify(),
data () {
return {
formDialog: {
inputs: {
definition: {
val: '', save: true, add: true,
icon: 'mdi-file-word',
placeholder: 'Word Definition'
},
synonym: {
val: '', save: true, add: true,
placeholder: 'Synonyms'
}
}
}
}
},
computed: {
initFields: function() {
let obj = {};
if(typeof this.formDialog.inputs != 'undefined') {
for(let key of Object.keys(this.formDialog.inputs)) {
if(typeof this.formDialog.inputs[key].val != 'undefined') {
//obj[key] = JSON.parse(JSON.stringify(this.formDialog.inputs[key]));
obj[key] = this.formDialog.inputs[key].val;
}
}
}
return JSON.parse(JSON.stringify(obj));
//return obj;
}
}
})
However the obj
object is retaining a shallow copy of the this.formDialog.inputs
object, when I expect it to make a deep copy of it. Why is it not creating a deep copy of the object even though I am using JSON.parse(JSON.stringify(obj))
?
Demonstration of issue: https://codepen.io/deftonez4me/pen/qBapYgP