難道你不只是使用默認值,並將它們設置爲null,如果屬性未定義在發佈數據?
//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對象的特定值,所以你可以爲他們被空添加一個檢查/未定義
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;
}
現在,你可以在所有航線使用。
var quote = validatePOST(req.body, [null, undefined]);
'author:req.body.author ||空'和是的,你可以檢查之後 – mplungjan
當你沒有定義源值時,你是否決定要使用這些屬性值? – Pointy
基本上我不希望這些值在那裏。這些來自一個稍後將值寫入數據庫的函數。如果我得到PUT請求中的值,我想更新它們,如果我不接受它們,我想讓它們保持原樣。 –