javascript - 对象分配键和值 - 如果值有效
问题描述
我认为这是肮脏/不需要的问题。
我有对象名称test,我只是尝试分配键和值(如果值有效)。
在下面的示例中,x,y,z 是变量,这些变量有时是动态的,有时只有我们得到值。
下面的代码工作正常,但我每次检查值是否有效时都会使用,然后我将键和值分配给对象。
只是我想检查一些添加密钥的聪明方法?
var test = {
a: "1",
b: "2"
}
var x = "3";
//here x value is dynamic, sometimes only we get value.
if (x) {
test.c = x;
}
var y = "4";
//here y value is dynamic, sometimes only we get value.
if (y) {
test.d = y;
}
var z = "5";
//here z value is dynamic, sometimes only we get value.
if (z) {
test.e = z;
}
console.log(JSON.stringify(test));
解决方案
如果在您的代码中,测试总是在添加到对象之前检查该值是否为真,您可以使用Proxy
:
const test = {
a: "1",
b: "2"
};
const testProx = new Proxy(test, {
set: (obj, prop, val) => {
if (val) obj[prop] = val;
}
});
testProx.c = 'foo';
testProx.d = null; // falsey, will fail the Proxy's test and will not be added to object
testProx.e = 'bar';
console.log(test);
如果您需要更复杂的验证,例如不同键的不同条件,我建议创建一个由键索引的对象,其中包含一个返回该键的值是否有效的函数:
const test = {
a: "1",
b: "2"
};
// just an example of having different conditions, this is not DRY code:
const testConditions = {
c: (v) => typeof v === 'string' && v[0] === 'c',
d: (v) => typeof v === 'string' && v[0] === 'd',
e: (v) => typeof v === 'string' && v[0] === 'e',
}
const testProx = new Proxy(test, {
set: (obj, prop, val) => {
if (testConditions[prop](val)) obj[prop] = val;
}
});
testProx.c = 'ccc';
// does not start with 'd', will fail the Proxy's test and will not be added to object:
testProx.d = 'fff';
testProx.e = 'eee';
console.log(test);
推荐阅读
- c# - 如何在 Visual Studio 2019 中将 wwwroot 目录添加到我的 WebAPI 项目
- java - 格式化日期以从年份编号中获取最后两位数字(例如:2019 年的 19)
- ios - Xcode 11,-[AppDelegate 窗口]:无法识别的选择器
- outlook-web-addins - 如何清理 Outlook 加载项的缓存?
- ios - 正在调用我的委托函数,但我的 UI 仍然没有相应更新
- python - 为分类帐创建自定义报告
- c# - 如何在 Elastic Search 中存储其他对象共有的对象?
- c# - 覆盖nuget包中的设置
- tinymce - 对于 TinyMCE 编辑器 - 如何允许格式化粘贴
- ios - 使用 AWS S3 上传文件在 Flutter 中返回空字符串