2017-05-24 96 views
0

我有這樣的對象:如何從對象中刪除未定義的屬性?

​​

現在有時會出現一些此酒店是不確定的。我想要的是如果其中一個this.prepaidDetailForm.prepaidDetails屬性未定義不顯示它們。因此,例如,如果this.prepaidDetailForm.prepaidDetails.firsName未定義,我不需要創建'firstName'屬性isnide對象。任何建議我該怎麼做?

+0

' if(typeof X!==「undefined」)this.prepaidObject [「key」] = X;' –

+0

爲什麼你想刪除添加屬性,如果你只能檢查和添加_「有效」_屬性? –

回答

4

檢查對象:

for(var m in this.prepaidObject) { 
     if (this.prepaidObject[m] == undefined) { 
      delete this.prepaidObject[m]; 
     } 
    } 
+0

我們可以循環對象嗎? –

+0

是的,在循環中,我發佈m成爲成員引用。 – SPlatten

+0

說實話,這對我來說是全新的,X'D,我認爲你可以用ES6的forEach(例如)做,但這樣我就不知道了。 –

0

您可能需要檢查類型。

(typeof(this.prepaidDetailForm.prepaidDetails.firsName) != "undefined") ? this.prepaidDetailForm.prepaidDetails.firsName : '' 

它基本上是:

var firstName = ''; 
if(typeof(this.prepaidDetailForm.prepaidDetails.firsName) != "undefined") 
    firstName = this.prepaidDetailForm.prepaidDetails.firsName; 
+0

這是一個調皮,它應該被自動踢出,而不是測試一個固定鍵的值。 ;) –

1

的方法之一是要經過鍵,只追加定義的:

this.prepaidObject = { }; 
Object.keys(this.prepaidDetailForm.prepaidDetails) 
    .forEach(function(key) { 
      var val = this.prepaidDetailForm.prepaidDetails[key]; 
      if (val !== undefined) { 
       this.prepaidObject[key] = val; 
      } 
    }); 

這是假設中的密鑰與prepaidDetails相同,它們都遵循您提到的相同規則。使用更多的功能ES6

this.prepaidObject = Object.keys(this.prepaidDetailForm.prepaidDetails) 
    .map(key => ({key, val: this.prepaidDetailForm.prepaidDetails[key]})) 
    .reduce((obj, {key, val}) => { 
      if (val !== undefined) { 
       obj[key] = val; 
      } 
      return obj; 
    }, {}); 

而且一個更簡潔的方法:

特別是如果你使用ES6你可能會使用mapreduce像這樣使這更優雅

this.prepaidObject = Object.keys(this.prepaidDetailForm.prepaidDetails) 
    .map(key => ({key, val: this.prepaidDetailForm.prepaidDetails[key]})) 
    .filter(({_, val}) => val !== undefined) 
    .reduce((obj, {key, val}) => Object.assign(obj, { [key]: val }), {}); 
0
this.prepaidObject = {}; 
for (var i in this.prepaidDetailForm.prepaidDetails) { 
    if (typeof(this.prepaidDetailForm.prepaidDetails[i]) !== 'undefined') { 
    this.prepaidObject[i] = this.prepaidDetailForm.prepaidDetails[i]; 
    } 
} 

如果您還想排除空值和未定義的條件更改爲:

if (this.prepaidDetailForm.prepaidDetails[i] != null) 

不是雙==。因爲null == undefinednull !== undefined

0

假設你有一個像下面的一個對象,

var prepaidObject = { 
    'customerType' : 'TestCustType', 
    'firstName' : "sample FirstName", 
    'lastName' : "sample LastName", 
    'note' : undefined 
}; 

可以使用JSON.parse和JSON除去不確定的。字符串化方法,

JSON.parse(JSON.stringify(prepaidObject)); 
console.log(prepaidObject) 

輸出將是,

{ 
    'customerType' : 'TestCustType', 
    'firstName' : "sample FirstName", 
    'lastName' : "sample LastName" 
} 
1

使用Lodash使它很容易在同一行:

_.pickBy(this.prepaidObject, _.identity); 

這將刪除所有falsey

相關問題