在javascript中,测试深度嵌套在对象图中的属性? [英] In javascript, test for property deeply nested in object graph?

查看:30
本文介绍了在javascript中,测试深度嵌套在对象图中的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 CouchDB 数据库中收集了一组不同的复杂 JSON 对象.每个都包含许多级别的嵌套属性——例如,

I've got a collection of disparate, complex JSON objects from a CouchDB database. Each contains many levels of nested properties--for example,

tps_report.personnel_info.productivity.units_sold = 8  

我想遍历这些对象并用它们做一些事情:例如,

I want to iterate through these objects and do stuff with them: for instance,

// writes units sold from each TPS report:
for (i in tpsReports) {
  if (tpsReports[i].personnel_info.productivity.units_sold < 10) {
    fireEmployee();
  }
}

问题是许多 TPS 报告没有设置所有这些属性.因此,如果我尝试这样做,当循环第一次到达没有personnel_info"属性的报告时,我会得到一个错误,从而尝试找到undefined"的productivity"属性.我宁愿发生的是条件只是跳过它并继续.

The problem is that many TPS reports don't have all these properties set. So if I try this, I'll get an error the first time the loop gets to a report without the "personnel_info" property and thus tries to find the "productivity" property of "undefined." What I'd rather happen is that the conditional just skips it and continues.

我看到了两种解决方法,这两种方法在我看来都很丑

I see two ways around this, both of which seem ugly to me

  1. 使用嵌套条件分别测试每个属性
  2. 将该行括在 try/catch 块中以捕获错误并忽略它

我更喜欢 PHP 的 isset() 函数之类的东西,无论您提供什么,它都不会抛出错误——它只会告诉您您要查找的特定变量是否存在或不是.所以,喜欢

What I'd prefer would be something like PHP's isset() function, which won't throw an error regardless of what you feed it--it'll just tell you whether the particular variable you're looking for exists or not. So, like

// writes units sold from each TPS report:
for (i in tpsReports) {
  if (isset(tpsReports[i].personnel_info.productivity.units_sold)){
    if (tpsReports[i].personnel_info.productivity.units_sold < 10) {
      fireEmployee();
    }
  }
}

有什么想法吗?

推荐答案

function isset(obj, propStr) {
    var parts = propStr.split(".");
    var cur = obj;
    for (var i=0; i<parts.length; i++) {
        if (!cur[parts[i]])
            return false;
        cur = cur[parts[i]];
    }
    return true;
}

请注意,第二个参数是一个字符串,因此在访问不存在的属性上的属性时不会引发异常.

Note that the second parameter is a string, so the exception doesn't get thrown when accessing a property on a nonexistent property.

这篇关于在javascript中,测试深度嵌套在对象图中的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆