2017-02-15 100 views
0

在編寫測試時,我JSON.stringify所有的輸入,並將其分配給一個對象作爲鍵寫一個對象作爲重點,然後分配鍵的實際值,像這樣:如何,如果屬性未定義

tests[JSON.stringify(test)] = test

問題是JSON.stringify({color: undefined}) = {}只是一樣的,如果JSON.stringify({}) = {}

任何人都有修改或不同的方法的想法?

+1

'JSON.stringify({ 'color':'undefined'})'? –

+0

'{color:null}','{color:false}'或'{color:''}'也可能有效。取決於JSON的目的。 –

回答

2

如果你不能改變性質或具有比其他undefined東西初始化它們,然後用replacer的傳球它stringify這樣的:

var obj = {key: "value", color: undefined, other: null}; 
 

 
// this function will be run over all key-value pairs in the object 
 
function replacer(key, value) { 
 
    if(value === undefined) // if the value is undefined 
 
    return 'undefined'; // then return a string 'undefined' (or null if you want) 
 
    return value; 
 
} 
 

 
// then pass replacer as second parameter to stringify 
 
var str = JSON.stringify(obj, replacer); 
 

 
console.log(str);