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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4676223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 14:31:36  来源:igfitidea点击:

Check if object member exists in nested object

javascriptobject

提问by JustcallmeDrago

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

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

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

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

回答by Felix Kling

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

通常,您可以使用if(property in object),但这对于嵌套成员来说仍然很麻烦。

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

演示

回答by Oscar Gillespie

You could also try/catch TypeError?

您也可以尝试/捕获 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);
  }
}

回答by user113716

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

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

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

alert( result );

回答by Ben

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

这里有一个 safeRead 函数定义在 thecodeabode 上,它允许对嵌套属性进行安全读取,即

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

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

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

回答by Malvolio

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

回答by Phrogz

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.

如果任何特定值碰巧是nullfalse0""(空字符串),这将不会“工作” ,但除了最终值可能是例外,这似乎不太可能。

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.

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

回答by kmonsoor

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

如果你可以使用lodash库,它有一个非常优雅的解决方案,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