[英]How to use Lodash when data is undefined or null
In my application If data is undefined or null which is coming from service, my html will not load and I will get "data is undefined" error so I am tring to use lodash, but dont know how to use it.. 在我的应用程序如果数据未定义或来自服务的null,我的html将无法加载,我将得到“数据未定义”错误,所以我想使用lodash,但不知道如何使用它..
In my below ts file 在我的下面的ts文件中
this._PartService.GetDataValues().subscribe(
result => {
this.distributionData = this._PartService.part_data.partMasterDataCompleteList[0].partMasterData.plantSupplies.plantSupply
}
I will be getting "partMasterDataCompleteList" as undefiend or null if data is not there, so there I am trying to use Lodash but I dont know how to use it 如果数据不存在,我将把“partMasterDataCompleteList”作为undefiend或null,所以我试图使用Lodash,但我不知道如何使用它
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. 虽然更好的方法是让服务器发送一个空数组而不是undefined或null。
This is not a lodash issue. 这不是一个问题。 It is just about handling the undefined or null case 它只是处理undefined或null的情况
您可能想要使用_.get函数。
this.distributionData = _.get(this, '_PartService.part_data.partMasterDataCompleteList[0].partMasterData.plantSupplies.plantSupply')
Lodash provides quite a few methods to check and get the value you want from an object. Lodash提供了很多方法来检查并从对象中获取所需的值。
_.get would actually return the value if it exists and would return undefined
if it does not. 如果值存在, __ get实际上将返回该值,如果不存在则返回undefined
。
_.has would check if the value exists and return true
if it does and false
if it does not. _.has会检查值是否存在 , 如果有 ,则返回true
否则返回false
。
_.hasIn would do the same as _.has
but would also check if this is an inherited property. _.hasIn将与_.has
相同,但也会检查这是否是继承的属性。
_.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 . _.result实际上会走路径并返回值,但有一个主要区别...... 它会执行任何函数来获取值 。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.