gpt4 book ai didi

javascript - 将对象内的所有元素分配给空字符串

转载 作者:行者123 更新时间:2023-12-01 02:24:01 26 4
gpt4 key购买 nike

我有一个错误对象:

data() {
return {
...
errors: {
login: {
email: '',
password: '',
},
register: {
name: '',
email: '',
password: '',
password_confirmation: '',
},
}
}
},

如何将 errors 对象内所有项目的值设置为 ''(只需清除它们)?
我可以使用
清除data对象内的所有项目Object.assign(this.$data, this.$options.data.call(this));
但是
Object.assign(this.$data.errors, this.$options.data.call(this));

Object.assign(this.$data.errors, {});

this.errors = ''

this.$set(this.$data.errors, '');
不起作用。

<小时/>

更新1
这适用于清除 errors.login:
Object.assign(this.$data.errors.login, this.$options.data.call(this));我想我可以将变量传递给 clear(obj) 并使用它
Object.assign(this.$data.errors.obj, this.$options.data.call(this));
但无论如何,寻找如何清除所有错误对象。

更新2
Object.assign(this.$data.errors.register, this.$options.data);
仅清除 errors.register 内的 emailpassword - 无法获取该逻辑。

最佳答案

您可以通过迭代对象的所有键并按对象值递归来采用迭代和递归方法。

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; }

关于javascript - 将对象内的所有元素分配给空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48962765/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com