JavaScript中测试对象链是否有效的好方法

5

考虑以下例子:

    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
你可以在if语句中使用&&运算符,像这样: 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 ''} - Kevin Kloet
请展示抛出的异常。你只说有异常,但那是什么呢? - user6360214
1
@SuperCoolHandsomeGelBoy 这将会是一个 TypeError,因为你试图访问一个 undefined 的属性。 - Madara's Ghost
2
你可以捕获异常 - GolezTrol
你想要测试哪一位呢?整个链条吗?所以这些对象中的任何一个都可能是“未定义”的? - Liam
显示剩余2条评论
3个回答

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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接