2017-09-06 34 views
-1

我想下面的代碼轉換爲使用lodash _.filter如何從使用lodash過濾器定義其值未定義的javascript對象中刪除屬性?

var substitutionValues = { one: "hi", two: undefined, three: 3}; 
var keys = _.keys(substitutionValues); 

for (var i = 0; i < keys.length; i++) { 
    if (substitutionValues[keys[i]] === undefined) { 
    delete substitutionValues[keys[i]]; 
    } 
} 

// => { one: "hi", three: 3 } 

請注意,我不希望使用lodash的_.reduce,_.pick,或_.omit東西。

+0

你可能想看看'pickBy'。您可以在遍歷對象屬性時指定條件,並使用它來過濾未定義的鍵。 https://lodash.com/docs/4.17.4#pickBy – Matthew

+2

這將是一個可怕的用例過濾器 –

+0

也檢查了這個相關的stackoverflow後:https://stackoverflow.com/questions/30726830/how-to- filter-keys-of-object-with-lodash – Matthew

回答

1

您可以使用_.pickBy()作爲對象的過濾器。由於_.pickBy()的默認謂詞是_.identity,因此它將過濾任何虛假值(第1個示例)。如果您想更具體,因此定義回調(第二個示例):

var substitutionValues = { one: "hi", two: undefined, three: 3, four: null }; 
 

 
/** 1st example **/ 
 
var widthoutAllFalsyValues = _.pickBy(substitutionValues); 
 

 
console.log(widthoutAllFalsyValues); 
 

 
/** 2nd example **/ 
 
var widthoutUndefined = _.pickBy(substitutionValues, _.negate(_.isUndefined)); 
 

 
console.log(widthoutUndefined);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

要使用過濾器,你會已通過使用類似對象轉換爲數組_.entries()(保存鍵),然後過濾的條目,並返回減少到一個對象:

var substitutionValues = { one: "hi", two: undefined, three: 3, four: null }; 
 

 
var result = _(substitutionValues) 
 
    .entries() 
 
    .filter(([k, v]) => !_.isUndefined(v)) 
 
    .reduce((o, [k, v]) => { 
 
    o[k] = v; 
 
    return o; 
 
    }, {}); 
 
    
 
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

相關問題