How to use Lodash when data is undefined or null

谁都会走 提交于 2019-12-22 05:19:42

问题


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..

In my below ts file

    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


回答1:


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>



回答2:


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




回答3:


You may want to use the _.get function.

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


来源:https://stackoverflow.com/questions/51780028/how-to-use-lodash-when-data-is-undefined-or-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!