2016-11-22 56 views
5

考虑这个例子:很好的方式,如果在JavaScript对象链是有效

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 ''; 

我想知道,如果它能够简化我在做什么在这里。

我的目标是测试对象链this.plantService.plants[id].Name[0]的有效性。

但是,如果我只测试if(this.plantService.plants[id].Name[0]) {...}异常被抛出。

任何建议? :)

+2

您可以使用'&&'op erator在你的如果是这样的:'if(this.plantService.plants [id] && this.plantService.plants [id] .Name && this.plantService.plants [id] .Name [0]){return this.plantService。植物[id] .Name [0] .value} else {return''}' –

+0

请向我们展示抛出的异常。你只是说有,但那是什么? –

+1

@SuperCoolHandsomeGelBoy这将是一个'TypeError',因为您试图访问'undefined'上的属性。 –

回答

4

你可以减少与对象数组,检查值后并键入。

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'));

+1

对我来说可能是最好的方式......但我希望有更好的东西:) – David

2

你可以在自己喜欢写一个简单的功能,

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

    return obj || defaultValue; 
} 

现在你可以这样调用它,

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

你可以试试这个:

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 ''; 
} 

或者,也许你的问题是,你的模型是不完整的,你需要确保的是,为了防止这些验证并用此代替:

return this.plantService.plants[id].Name[0].value; 
相关问题