如何在数据未定义或为null时使用Lodash [英] How to use Lodash when data is undefined or null
问题描述
在我的应用程序中如果数据未定义或来自服务的null,我的html将无法加载,我将得到数据未定义错误
因此我想使用lodash,但不知道如何使用它..
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..
在我的下面的ts文件中
In my below ts file
this._PartService.GetDataValues().subscribe(
result => {
this.distributionData = this._PartService.part_data.partMasterDataCompleteList[0].partMasterData.plantSupplies.plantSupply
}
我将获取partMasterDataCompleteList作为undefiend,如果数据不存在则为null,所以我试图使用Lodash但我不知道如何使用它
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
推荐答案
Lodash提供了很多方法来检查并从对象中获取所需的值。
Lodash provides quite a few methods to check and get the value you want from an object.
_.get 实际上返回值(如果存在)并返回 u ndefined
如果没有。
_.get would actually return the value if it exists and would return undefined
if it does not.
_.has 将检查值是否存在并返回 true
如果是, false
如果确实如此不是。
_.has would check if the value exists and return true
if it does and false
if it does not.
_.hasIn 将与 _。
相同,但也会检查这是否为继承属性。
_.hasIn would do the same as _.has
but would also check if this is an inherited property.
< a href =https://lodash.com/docs/4.17.10#result =nofollow noreferrer> _。结果实际上会走路径并返回值但主要区别... 它会在获取值的方式中执行任何功能。
_.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.
示例:
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>
这篇关于如何在数据未定义或为null时使用Lodash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!