1👍
You could take an iterative and recursive approach by iterating all keys of the object and recursive by object values.
function empty(object) {
Object.keys(object).forEach(function (k){
if (object[k] && typeof object[k] === 'object') {
return empty(object[k]);
}
object[k] = '';
});
}
var object = { errors: { login: { foo: 43, bar: 23 }, register: { baz: 'aaa', inner: { key: 'value' } } } };
empty(object);
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
1👍
Solved.
In fact no need to do some recursive stuff or whatever. Just:
- Declare
errors
atnull
in your data’s component - Declare a
resetErrors()
method who instanciatethis.errors
like you want, and call that function when your component iscreated()
- Call
this.resetErrors()
whenever you want to reset/clear your errors object.
const app = new Vue({
el: '#app',
data() {
return {
errors: null
}
},
methods: {
resetErrors() {
this.errors = {
login: {
email: '',
password: '',
},
register: {
name: '',
email: '',
password: '',
password_confirmation: '',
}
}
}
},
created() {
this.resetErrors();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.min.js"></script>
<div id="app">
<button @click="resetErrors">
Clear errors
</button>
<pre>
{{ errors }}
</pre>
</div>
Source:stackexchange.com