检查嵌套对象中是否存在对象成员

发布于 2024-10-12 08:38:25 字数 150 浏览 4 评论 0原文

有没有比使用 ___ in object 检查对象的每个级别是否存在来检查单个成员是否存在更简单的方法?

更简洁:如何检查 someObject.member.member.member.value 是否存在?

Is there a simpler way than using ___ in object to check the existence of each level of an object to check the existence of a single member?

More concisely: How can I check if someObject.member.member.member.value exists?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

流绪微梦 2024-10-19 08:38:25

一般来说,您可以使用if(object中的property),但这对于嵌套成员来说仍然很麻烦。

您可以编写一个函数:

function test(obj, prop) {
    var parts = prop.split('.');
    for(var i = 0, l = parts.length; i < l; i++) {
        var part = parts[i];
        if(obj !== null && typeof obj === "object" && part in obj) {
            obj = obj[part];
        }
        else {
            return false;
        }
    }
    return true;
}

test(someObject, 'member.member.member.value');

DEMO

In general, you can use if(property in object), but this would be still cumbersome for nested members.

You could write a function:

function test(obj, prop) {
    var parts = prop.split('.');
    for(var i = 0, l = parts.length; i < l; i++) {
        var part = parts[i];
        if(obj !== null && typeof obj === "object" && part in obj) {
            obj = obj[part];
        }
        else {
            return false;
        }
    }
    return true;
}

test(someObject, 'member.member.member.value');

DEMO

羅雙樹 2024-10-19 08:38:25

您还可以尝试/捕获 TypeError?

try {
  console.log(someObject.member.member.member.value);
} catch(e) {
  if (e instanceof TypeError) {
    console.log("Couldn't access someObject.member.member.member.value");
    console.log(someObject);
  }
}

You could also try/catch TypeError?

try {
  console.log(someObject.member.member.member.value);
} catch(e) {
  if (e instanceof TypeError) {
    console.log("Couldn't access someObject.member.member.member.value");
    console.log(someObject);
  }
}
み青杉依旧 2024-10-19 08:38:25

这是一种方法: http://jsfiddle.net/9McHq/

var result = ((((someObject || {}).member || {}).member || {}).member || {}).value;

alert( result );

Here's one way: http://jsfiddle.net/9McHq/

var result = ((((someObject || {}).member || {}).member || {}).member || {}).value;

alert( result );
恋你朝朝暮暮 2024-10-19 08:38:25
if (someObject.member && someObject.member.member &&
    someObject.member.member.member && someObject.member.member.member.value) ...

或类似:

var val = foo.bar && foo.bar.jim && foo.bar.jim.jam && foo.bar.jim.jam.value;

如果任何特定值恰好为 nullfalse0""< /code> (空字符串),但除了最终值可能存在的例外之外,情况似乎不太可能如此。

另请注意,typeof ____ !== "undefined" 并不是判断对象是否具有属性的正确测试。相反,您应该使用___ in object,例如if ("member" in someObject)。这是因为您可以将属性设置为显式值 undefined,这与使用 delete someObject.member 删除它不同。

if (someObject.member && someObject.member.member &&
    someObject.member.member.member && someObject.member.member.member.value) ...

or similarly:

var val = foo.bar && foo.bar.jim && foo.bar.jim.jam && foo.bar.jim.jam.value;

This will not 'work' if any particular value happens to be null, false, 0, or "" (an empty string), but with the possible exception of the final value, this seems unlikely to be the case.

Also, note that typeof ____ !== "undefined" is not the correct test to see if an object has a property. Instead you should use ___ in object, e.g. if ("member" in someObject). This is because you can set a property to an explicit value of undefined, which is different from removing it with delete someObject.member.

地狱即天堂 2024-10-19 08:38:25

类似于(警告:前面未经测试的代码)

var testProperty = function(obj, proplist) {
   for (var i=0; i < proplist.length; i++) {
      if (obj.hasOwnProperty(proplist[i])) {
         obj = obj[proplist[i]];
      } else {
        return false;
      }
   }
   return true;
}

Something like (warning: untested code ahead)

var testProperty = function(obj, proplist) {
   for (var i=0; i < proplist.length; i++) {
      if (obj.hasOwnProperty(proplist[i])) {
         obj = obj[proplist[i]];
      } else {
        return false;
      }
   }
   return true;
}
冷清清 2024-10-19 08:38:25

在 thecodeabode 上定义了一个 safeRead 函数允许安全读取嵌套属性
即,

safeRead(foo, 'bar', 'jim', 'jam');

如果任何属性为空或未定义,则返回空白字符串 - 对于格式化/字符串插值很有用

Theres a safeRead function defined here on thecodeabode which allows a safeRead of nested properties
i.e.

safeRead(foo, 'bar', 'jim', 'jam');

if any of the properties are null or undefined a blank string is returned - useful for formatting / string interpolation

悲喜皆因你 2024-10-19 08:38:25

如果您可以使用lodash库,它有一个非常优雅的解决方案,hasIn

_.hasIn(someObject, 'member.level1.level2.level3');

例如,

var obj = {'x': 999, 'a': {'b': {'c': 123, 'd': 234}}}
// => undefined

_.hasIn(obj, 'x')
// => true

_.hasIn(obj, 'a.b.d')
// => true

_.hasIn(obj, 'a.b.e')
// => false

If you can use lodash library, it has a very elegant solution, hasIn.

_.hasIn(someObject, 'member.level1.level2.level3');

for example,

var obj = {'x': 999, 'a': {'b': {'c': 123, 'd': 234}}}
// => undefined

_.hasIn(obj, 'x')
// => true

_.hasIn(obj, 'a.b.d')
// => true

_.hasIn(obj, 'a.b.e')
// => false
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文