JS对象具有属性深层检查 [英] JS object has property deep check

查看:127
本文介绍了JS对象具有属性深层检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有JS对象:

var object = {
   innerObject:{
       deepObject:{
           value:'Here am I'
       }
   }
};

我们如何检查属性是否存在?
我只能看到两种方式:

How can we check if value property exists? I can see only two ways:

第一个:

if(object && object.innerObject && object.innerObject.deepObject && object.innerObject.deepObject.value) {
    console.log('We found it!');
}

第二个:

if(object.hasOwnProperty('innerObject') && object.innerObject.hasOwnProperty('deepObject') && object.innerObject.deepObject.hasOwnProperty('value')) {
    console.log('We found it too!');
}

但有没有办法进行深入检查?让我们说,比如:

But is there a way to do a deep check? Let's say, something like:

object['innerObject.deepObject.value']

object.hasOwnProperty('innerObject.deepObject.value')


推荐答案

没有这种检查的内置方式,但您可以轻松实现它。创建一个函数,传递一个表示属性路径的字符串,通过拆分路径并迭代这条路径:

There isn't a built-in way for this kind of check but you can implement it easily. Create a function, pass a string representing the property path, split the path by . and iterate over this path:

Object.prototype.hasOwnNestedProperty = function(propertyPath){
    if(!propertyPath)
        return false;

    var properties = propertyPath.split('.');
    var obj = this;

    for (var i = 0; i < properties.length; i++) {
        var prop = properties[i];

        if(!obj || !obj.hasOwnProperty(prop)){
            return false;
        } else {
            obj = obj[prop];
        }
    }

    return true;
};

// Usage: 
var obj = {
   innerObject:{
       deepObject:{
           value:'Here am I'
       }
   }
}

obj.hasOwnNestedProperty('innerObject.deepObject.value');

这篇关于JS对象具有属性深层检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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