我认为这是肮脏/不需要的问题。
我有对象名称test,我只是尝试分配键和值(如果值有效)。
在下面的示例中,x、y、z 是变量,这些变量是动态的,有时只有我们获得值。
下面的代码工作正常,但我每次检查值是否有效时都使用,然后将键和值分配给对象。
只是我想检查一些添加 key 的智能方法?
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));
最佳答案
如果像在您的代码中一样,测试总是在添加到对象之前检查该值是否为真,那么您可以使用代理
:
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);
关于javascript - 对象分配键和值 - 如果值有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51298586/