【问题标题】:How to use Lodash when data is undefined or null当数据未定义或为空时如何使用 Lodash
【发布时间】:2019-01-17 16:29:11
【问题描述】:

在我的应用程序中,如果来自服务的数据未定义或为空,我的 html 将不会加载,我将收到“数据未定义”错误 所以我想用lodash,但不知道怎么用..

在我下面的 ts 文件中

    this._PartService.GetDataValues().subscribe(
  result => {
    this.distributionData = this._PartService.part_data.partMasterDataCompleteList[0].partMasterData.plantSupplies.plantSupply
  }

如果数据不存在,我将得到“partMasterDataCompleteList”作为 undefiend 或 null,所以我正在尝试使用 Lodash,但我不知道如何使用它

【问题讨论】:

  • 尝试使用 lodash 是什么意思?
  • 如果它可以是未定义的,你应该处理这种情况。

标签: javascript angular typescript angular5 lodash


【解决方案1】:

Lodash 提供了很多方法来检查并从对象中获取所需的值。

_.get 实际上会返回值(如果存在),如果不存在则返回undefined

_.has检查该值是否存在,如果存在则返回 true,如果不存在则返回 false

_.hasIn 将与_.has 执行相同的操作,但还会检查这是否是继承属性。

_.result 实际上会走路径并返回值,但有一个主要区别...... 它将执行任何函数以获取值

例子:

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>

【讨论】:

    【解决方案2】:

    您可能想要使用_.get 函数。

    this.distributionData = _.get(this, '_PartService.part_data.partMasterDataCompleteList[0].partMasterData.plantSupplies.plantSupply')
    

    【讨论】:

    • 是的 - 并在之前导入。在这种情况下,名称为 _
    • 我有“let temp = []; this.weight = temp”,这里的 temp 是一个数组,那么我该如何使用 ._get 这个数组
    • 我可以使用 ._get 来执行以下代码 this.PartServiceData.masterData = result['data'].partMasterDataCompleteList[0];
    【解决方案3】:

    为了处理未定义的情况,我使用以下方法:

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

    虽然更好的方法是让服务器发送一个空数组而不是 undefined 或 null。

    这不是 lodash 问题。它只是处理未定义或空的情况

    【讨论】:

    • 谢谢..它工作但对于每个对象我需要继续添加空对象所以我尝试使用 Lodash..如果你知道请告诉我
    • lodash .get 对象函数可能会起作用。见lodash.com/docs/4.17.10#get
    猜你喜欢
    • 1970-01-01
    • 2022-11-04
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 2021-12-16
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多