How to use Lodash when data is undefined or null

浪子不回头ぞ 提交于 2019-12-05 06:05:35

Lodash provides quite a few methods to check and get the value you want from an object.

_.get would actually return the value if it exists and would return undefined if it does not.

_.has would check if the value exists and return true if it does and false if it does not.

_.hasIn would do the same as _.has but would also check if this is an inherited property.

_.result would actually walk the path and return the value as well but with a major difference ... it would execute any function among the way to get to the value.

Examples:

var data = { more: { result: 1}}
var data2 = _.create({ 'more': _.create({ 'result': 2 }) });
var data3 = { more: function() { return { result: 1} }}

console.log(_.get(data, 'more.result'))     // 1
console.log(_.has(data, 'more.result'))     // true
console.log(_.hasIn(data2, 'more.result'))  // true
console.log(_.result(data3, 'more.result')) // 1
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

To handle undefined cases, I use the following :

this.distributionData =((((this._PartService.part_data.partMasterDataCompleteList || [])[0] || {}).partMasterData || {}).plantSupplies || {}).plantSupply

Although a better approach would be to have the server send an empty array instead of undefined or null.

This is not a lodash issue. It is just about handling the undefined or null case

You may want to use the _.get function.

this.distributionData = _.get(this, '_PartService.part_data.partMasterDataCompleteList[0].partMasterData.plantSupplies.plantSupply')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!