如何在数据未定义或为空时使用 Lodash [英] How to use Lodash when data is undefined or 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 实际上会返回值如果它存在并且将返回 undefined
如果它不存在.
_.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 与 _.has
但也会检查这是否是继承的属性.
_.hasIn would do the same as _.has
but would also check if this is an inherited property.
_.result 实际上会走路径并返回值,但是有一个主要区别...... 它会在获取价值的方式中执行任何功能.
_.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>
这篇关于如何在数据未定义或为空时使用 Lodash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!