我有這樣的對象:如何從對象中刪除未定義的屬性?
現在有時會出現一些此酒店是不確定的。我想要的是如果其中一個this.prepaidDetailForm.prepaidDetails
屬性未定義不顯示它們。因此,例如,如果this.prepaidDetailForm.prepaidDetails.firsName
未定義,我不需要創建'firstName'
屬性isnide對象。任何建議我該怎麼做?
我有這樣的對象:如何從對象中刪除未定義的屬性?
現在有時會出現一些此酒店是不確定的。我想要的是如果其中一個this.prepaidDetailForm.prepaidDetails
屬性未定義不顯示它們。因此,例如,如果this.prepaidDetailForm.prepaidDetails.firsName
未定義,我不需要創建'firstName'
屬性isnide對象。任何建議我該怎麼做?
檢查對象:
for(var m in this.prepaidObject) {
if (this.prepaidObject[m] == undefined) {
delete this.prepaidObject[m];
}
}
我們可以循環對象嗎? –
是的,在循環中,我發佈m成爲成員引用。 – SPlatten
說實話,這對我來說是全新的,X'D,我認爲你可以用ES6的forEach(例如)做,但這樣我就不知道了。 –
您可能需要檢查類型。
(typeof(this.prepaidDetailForm.prepaidDetails.firsName) != "undefined") ? this.prepaidDetailForm.prepaidDetails.firsName : ''
它基本上是:
var firstName = '';
if(typeof(this.prepaidDetailForm.prepaidDetails.firsName) != "undefined")
firstName = this.prepaidDetailForm.prepaidDetails.firsName;
這是一個調皮,它應該被自動踢出,而不是測試一個固定鍵的值。 ;) –
的方法之一是要經過鍵,只追加定義的:
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你可能會使用map
和reduce
像這樣使這更優雅
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 }), {});
請請嘗試以下方法:
for (var propName in this.prepaidObject) {
if (this.prepaidObject[propName] === undefined) {
delete this.prepaidObject[propName];
}
}
And lo確定在以下答案: Remove blank attributes from an Object in Javascript
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 == undefined
但null !== undefined
假設你有一個像下面的一個對象,
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"
}
' if(typeof X!==「undefined」)this.prepaidObject [「key」] = X;' –
爲什麼你想刪除添加屬性,如果你只能檢查和添加_「有效」_屬性? –