2014-07-22 32 views
0

我使用下面得到一些數據,並將其加載到一個對象:如何將對象內的數組內容設置爲false,如果它爲空?

test.qs = data; 

對象QS然後看起來是這樣的:

[ 
{"answer":null, 
    "answered":true, 
    // many more fields here 
    "answers":{"correct":null,"response":null}}, 
{"answer":null, 
    "answered":true, 
    // many more fields here 
    "answers":{"correct":null,"response":null}} 
] 

我怎樣才能讓這個如果數組中的響應值爲null,那麼它變成false?

+1

爲什麼要將'null'更改爲'false'?他們不傳達相同的信息。我嗅到了麻煩......我寧願修正生成數據的代碼,如果你真的想'假'。 – elclanrs

+0

它正在填充一個複選框,如果尚未點擊,該複選框的值將爲false。 – Alan2

回答

1
var x=[ 
{"answer":null, 
    "answered":true, 
    // many more fields here 
    "answers":{"correct":null,"response":null}}, 
{"answer":null, 
    "answered":true, 
    // many more fields here 
    "answers":{"correct":null,"response":null}} 
]; 
var string=JSON.stringify(x).toString().replace(/\:null/g, ":false"); 
var json=jQuery.parseJSON(string); 

這將改變所有空值爲假

0

試試這個:

$(test.qs).each(function() { 
    $(this).each(function (i) { 
    for(var props in this) { 
     if(test.qs[i][props] == null) 
     test.qs[i][props] = false; 
    } 
    }); 
}); 

注:

您需要的jQuery取決於你在哪裏考取代碼執行這段代碼+,它應該是在全球上市,所以,如果代碼沒有按「T工作添加下一個在您的變量聲明:

window.test = test; 
0

據我所知:如果您希望將「response」的值更改爲false,如果其值爲「null」。假設陣列中的每個對象都具有相同的結構,則應該如此工作:

for(var i = 0; i < test.qs.length; ++i) 
{ 
    if(test.qs[i]["answers"]["response"] == null) 
    { 
     test.qs[i]["answers"]["response"] = false; 
    } 
} 
相關問題