我有以下变量:
const quote = {
author: req.body.author,
quote: req.body.quote,
source: req.body.source,
updatedAt: Date.now(),
};
我只想分配已定义的值。例如,我可以检查是否未定义:
if(req.body.author === undefined) {
console.log('author undefined');
}
但是我如何将其转化为不赋值呢?如果 undefined
,我是否需要事后检查然后删除该属性?
最佳答案
如果属性在发布数据中未定义,你能不能只使用默认值并将它们设置为空?
//Unsure if you want the default value to have any meaning
//using null would likely achieve what you're asking.
var default_value = null;
const quote = {
author: req.body.author || default_value,
quote: req.body.quote || default_value,
source: req.body.source || default_value,
updatedAt: Date.now(),
};
如果你真的想去除它们,这里有一个你可以在之后使用的基本循环。
for (var i in quote) {
if (quote[i] == default_value) {
//Unsure how this works with const... might have to change to var
delete quote[i];
}
}
或者,您可以遍历 req.body 对象,避免在初始声明后进行验证。
var quote = {};
for (var i in req.body) {
quote[i] = req.body[i];
}
不确定您是否仍要针对 req.body 对象中的某些值进行验证,以便您可以添加检查它们是否为 null/undefined
var quote = {};
for (var i in req.body) {
//This will only declare the value on the quote object if the value
//is not null or undefined. False could be a value you're after so
//I avoided using the cleaner version of 'if (!req.body[i]) ...'
if (req.body[i] !== null || req.body[i] !== undefined) {
quote[i] = req.body[i];
}
}
你甚至可以把它分解成一个很好的可重用函数(下面的基本实现):
//Obj would be your post data
//bad_values would be an array of values you're not interested in.
function validatePOST (obj, bad_values) {
var data = {};
for (var i in obj) {
//Check the value isn't in the array of bad values
if (bad_values.indexOf(obj[i]) === -1) {
data[i] = obj[i];
}
}
//Return the validated object
return data;
}
现在您可以在所有 route 使用它。
var quote = validatePOST(req.body, [null, undefined]);
关于javascript - 仅在定义时分配属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40467563/