代码之家  ›  专栏  ›  技术社区  ›  DavidDunham

Object.hasOwnProperty属性多个级别无错误[重复]

  •  0
  • DavidDunham  · 技术社区  · 6 年前

    我想知道是否有某种方法可以将hasOwnProperty用于多个级别的对象。

    举例说明:

    var Client = {
        ID: 1,
        Details: {
            Title: 'Dr',
            Sex: 'male'
        }
    }
    

    我现在可以在javascript中执行以下操作:

    ('Title' in Client.Details) -> true
    

    但是我不能!执行:

    ('Street' in Client.Adress)
    

    …但我必须先使用if来避免抛出错误。因为我可能有一个很大的物体-我只需要知道里面是否有“地址”客户。详细信息如果不使用先前的if语句,有没有可能的想法?

    // this is overkill -> (will be many more if-statements for checking a lower level
    if('Adress' in Client){
        console.log('Street' in Client.Adress)
    } else {
        console.log(false)
    }
    

    var Client = {
        ID: 1,
        Details: {
            Title: 'Dr',
            Sex: 'male'
        }
    }
    
    // Results in Error:
    ('Street' in Client.Adress)
    
    // Results in Error:
    if('Street' in Client.Adress){}
    1 回复  |  直到 6 年前
        1
  •  2
  •   Zenoo    6 年前

    您可以通过 String 并使用递归函数运行对象:

    const checkPath = (o, path) => {
      if(path.includes('.')){
        if(o.hasOwnProperty(path.split('.')[0])) return checkPath(o[path.split('.')[0]], path.split('.').slice(1).join('.'));
        else return false
      }else return o.hasOwnProperty(path);
    }
    

    像这样使用:

    checkPath(Client, 'Details.Title')
    

    let Client = {
        ID: 1,
        Details: {
            Title: 'Dr',
            Sex: 'male'
        }
    };
    
    const checkPath = (o, path) => {
      if(path.includes('.')){
        if(o.hasOwnProperty(path.split('.')[0])) return checkPath(o[path.split('.')[0]], path.split('.').slice(1).join('.'));
        else return false
      }else return o.hasOwnProperty(path);
    }
    
    console.log(checkPath(Client, 'Details.Title'));
    console.log(checkPath(Client, 'Test.Title'));

    下面是性感的一句台词:

    const checkPath = (o, path) => path.includes('.') ? o.hasOwnProperty(path.split('.')[0]) ? checkPath(o[path.split('.')[0]], path.split('.').slice(1).join('.')) : false : o.hasOwnProperty(path);
    
    推荐文章