首页 > 解决方案 > 对象分配键和值 - 如果值有效

问题描述

我认为这是肮脏/不需要的问题。

我有对象名称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));

标签: javascriptobject

解决方案


如果在您的代码中,测试总是在添加到对象之前检查该值是否为真,您可以使用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);


推荐阅读