2016-08-11 39 views
1

我有一個對象數組,我想從任何對象的任何屬性中刪除'undefined'。查看對象數組並從中刪除未定義的屬性

從對象,我用這個方法去除不確定的,

removeNullorUndefined:function(model) { 
       function recursiveFix(o) { 
        // loop through each property in the provided value 
        for (var k in o) { 
         // make sure the value owns the key 
         if (o.hasOwnProperty(k)) { 
          if (o[k] === 'undefined') { 
           // if the value is undefined, set it to 'null' 
           o[k] = ''; 
          } else if (typeof (o[k]) !== 'string' && o[k].length > 0) { 
           // if there are sub-keys, make a recursive call 
           recursiveFix(o[k]); 
          } 
         } 
        } 
       } 

       var cloned = $.extend(true, {}, model); 
       recursiveFix(cloned); 
       return cloned; 

     }, 

我怎麼能修改此所以它也可以接受對象的數組,並從中取出「未定義」?

欣賞任何輸入

+1

是不是故意的,你使用一個字符串' 'undefined''而不是一個文字'undefined'?你也將它設置爲一個空字符串,而不是'null'(它仍然是一個字符串,與不帶'null的不帶引號相同) – 4castle

回答

3

只要該值undefined而不是「未定義」,其中一個方法是使用JSON.stringify一個字符串值。參考屬性值:

如果未定義,函數,或一個符號轉換期間遇到它要麼省略(當它在一個對象被發現)或截尾爲null(當它在陣列中被發現) 。 JSON.stringify也可以在傳遞「純」值(如JSON.stringify(function(){})或JSON.stringify(undefined)時返回undefined。

因此,您可以將對象串聯起來,並立即解析它以刪除undefined值。

注意:此方法將深入克隆整個對象。換句話說,如果需要維護引用,這種方法將不起作用。

var obj = { 
 
    foo: undefined, 
 
    bar: '' 
 
}; 
 
var cleanObj = JSON.parse(JSON.stringify(obj)); 
 

 
// For dispaly purposes only 
 
document.write(JSON.stringify(cleanObj, null, 2));

另外一個好處是,沒有任何特殊的邏輯將在任何深入的工作:

var obj = { 
 
    foo: { 
 
    far: true, 
 
    boo: undefined 
 
    }, 
 
    bar: '' 
 
}; 
 
var cleanObj = JSON.parse(JSON.stringify(obj)); 
 

 
// For dispaly purposes only 
 
document.write(JSON.stringify(cleanObj, null, 2));

如果它是一個字符串值「未定義「,您可以使用相同的方法,但使用replacer個功能:

var obj = { 
 
    foo: { 
 
    far: true, 
 
    boo: 'undefined' 
 
    }, 
 
    bar: '' 
 
}; 
 
var cleanObj = JSON.parse(JSON.stringify(obj, replacer)); 
 

 
function replacer(key, value) { 
 
    if (typeof value === 'string' && value === 'undefined') { 
 
    return undefined; 
 
    } 
 

 
    return value; 
 
} 
 

 
// For dispaly purposes only 
 
document.write(JSON.stringify(cleanObj, null, 2));

+0

如果'undefined'實際上是一個字符串在問題中。 – 4castle

+0

@ 4caste謝謝,忘了補充一點。現在修復。 –

1

如果你喜歡removeNullorUndefined()當前工作,然後你的方法可以嘗試:

items.forEach(function(item){ removeNullorUndefined(item); }); 
相關問題