2013-11-27 27 views
0
設置創建一個數組

所以我有5個變量:我怎麼能依靠,如果變量在jQuery的

var item_id 
var status 
var next_contact 
var email 
var phone_number 
var comment 

這些在POST請求在陣列發送到我的服務器:

d = {'item_id': item_id, 'status': status, 'next_contact': next_contact, 'email': email, 'phone_number': phone_number, 'comment': comment} 

在發出請求之前,我想檢查哪些變量是空的,如果它們是空的,我想從POST請求中刪除它們。

怎麼能以最簡潔的方式實現這一目標?

我想這樣做這樣每個變量的:

d = []; 

if(email != '') { 
    d.push('email': email); 
} 

這是一個好主意嗎?

謝謝!

+0

@lsmailp,澄清,你已經創建了'd'? – Andy

+0

是的,我有。但是如果有創建它的方式可能會更清潔? – Ismailp

+0

首先創建一個對象而不是所有變量,然後訪問對象屬性,如下所示:'obj.item_id ='thing'',然後當您想要將它關閉時,更容易循環和連續。 – Andy

回答

2

由於d對象,你可以在它移除,該值爲null或空屬性循環:

for (var k in d) { 
    if (d[k] === null || d[k] === '') delete d[k]; 
} 
+0

我想他是在討論如何根據變量創建'd',不是嗎? – talemyn

+0

是的,但是這個解決方案也適用。 – Ismailp

0

另一種方法是使一個item對象,並分配變量作爲屬性。然後,您可以使用函數來遍歷此對象,並將值作爲可以傳遞給POST請求的另一個對象返回。

// this would make a nice "class" or model 
var item = {}; 

item.id = 1; 
item.status = "complete"; 
item.email = undefined; 
item.null = null; 
item.empty = ''; 
// etc... 

// get non falsey values 
function getValues(item) { 
    var values = {}; 
    for (var prop in item) { 
    if (item.hasOwnProperty(prop) && item[prop]) { 
     values[prop] = item[prop]; 
    } 
    } 
    return values; 
} 

d = getValues(item); 
console.log(d); // {id: 1, status: "complete"} 
相關問題