0

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

举例说明:我有以下对象:

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

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

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

然而我不能!做:

('Street' in Client.Adress)

...但我必须首先使用 if 才能不引发错误。因为我可能有一个大对象 - 我只需要知道 Client.Details 中是否有“地址”而不使用之前的 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){}

4

1 回答 1

4

您可以通过 a 传递属性的路径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);
于 2018-09-13T13:53:38.413 回答