Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 351
sneha mahalank Avatar asked Aug 10 '18 06:08

sneha mahalank


2 Answers

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>
like image 72
Akrion Avatar answered Oct 05 '22 13:10

Akrion


You may want to use the _.get function.

this.distributionData = _.get(this, '_PartService.part_data.partMasterDataCompleteList[0].partMasterData.plantSupplies.plantSupply')
like image 28
kearnmachine Avatar answered Oct 05 '22 13:10

kearnmachine