A good way to check if a chain of objects is correct in JavaScript

Given this example:

if(this.plantService.plants[id]) { if(this.plantService.plants[id].Name) { if(this.plantService.plants[id].Name[0]) return this.plantService.plants[id].Name[0].value; else return ''; } else return ''; } return ''; 

I am wondering if I can simplify what I am doing here.

My goal is to check the integrity of the this.plantService.plants[id].Name[0] object.

However, if I just test if(this.plantService.plants[id].Name[0]) {...} , exceptions will be thrown.

Any suggestions?:)

+5
source share
3 answers

You can reduce the array with an object after checking the value and type.

 function getIn(object, keys, def) { return keys.reduce(function (o, k) { return o && typeof o === 'object' && k in o ? o[k] : def; }, object); } var object = { plantService: { plants: [{ Name: [{ value: 42 }] }] } }; console.log(getIn(object, ['plantService', 'plants', 0, 'Name', 0, 'value'], 'default value')); console.log(getIn(object, ['b', 'c', 'd', 'e'], 'default value')); 
+4
source

You can write a simple function yourself, for example,

 function getVal(obj, propQueue, defaultValue) { for (var prop of propQueue) { if ((obj = obj[prop]) === undefined) { break; } } return obj || defaultValue; } 

Now you can call him

 var value = getVal(this, ["plantService", "plants", id, "name" 0], ""); console.log(value); //either "" or the real value. 
+2
source

You can try the following:

 if(this.plantService.plants[id] && this.plantService.plants[id].Name && this.plantService.plants[id].Name[0]){ return this.plantService.plants[id].Name[0].value; }else{ return ''; } 

Or maybe your problem is that your model is not complete, and you should be sure of this in order to prevent these checks and replace with this:

 return this.plantService.plants[id].Name[0].value; 
0
source

Source: https://habr.com/ru/post/1260150/


All Articles