2016-11-07 23 views
1

分配財產,我有以下變量:只有定義

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,然後刪除財產?

+1

'author:req.body.author ||空'和是的,你可以檢查之後 – mplungjan

+0

當你沒有定義源值時,你是否決定要使用這些屬性值? – Pointy

+0

基本上我不希望這些值在那裏。這些來自一個稍後將值寫入數據庫的函數。如果我得到PUT請求中的值,我想更新它們,如果我不接受它們,我想讓它們保持原樣。 –

回答

2

難道你不只是使用默認值,並將它們設置爲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]); 
+0

與此問題是'默認'值寫入我的數據庫。所以如果請求中沒有任何內容,我不希望該屬性在那裏(因爲它會被覆蓋)。所以這將只是將我的數據庫中的新值設置爲null,如果沒有提供。 –

+0

檢查我剛剛發佈的循環 –

+0

是的,這樣的循環是我腦海中的基本想法。只是不知道是否有更簡單的方法,但適合我的目的。 –