javascript - 对象分配键和值 - 如果值有效

标签 javascript object

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

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

相关文章:

javascript - 我可以在 MooTools 中设置全局 fx 属性吗?

javascript - 带有指令的元素的加载事件

javascript - 如何在没有 css 的情况下检查鼠标是否在屏幕上的 "invisible"框内(JavaScript 和 jQuery)

php - $this 什么时候开始工作的?

javascript - JQuery 事件在 .addClass 之后不起作用

javascript - jQuery UI 对话框 - 关闭后不打开

javascript - 使用 Flask 检索本地存储数据

javascript - 检查object.property的值是value1还是value2

JavaScript 对象和方法,但 getName 不是函数

php - 为什么从 Json 对象插入数据不起作用?