在使用嵌套值之前,检查任何父对象是否不确定



,因为这种检查沿途检查每个对象的方法变得有些愚蠢:

const saved = profile && 
  profile.content && 
  question &&
  question.subject && 
  profile.content[question.subject] && 
  profile.content[question.subject].saved 
  ? 
  profile.content[question.subject].saved.includes(question._id) 
  : false

这样的东西会祝福:

const value = profile.content[question.subject].saved.includes(question._id)
if(value === defined) {
  // cool
}

我敢肯定,有一些可爱的东西,而es6'y却错过了较旧的问题。欢呼!

我只会定义一个函数,这使您可以通过所需的路径传递:

const get = (o, p) =>
         p.split('.').reduce((xs, x) => (xs && xs[x]) ? xs[x] : undefined, o)
    
const testData = {
    a: {
        b: {
            c: 'd',
            e: 'f',
            h: 'i'
        },
        j: 'k'
   }
}
console.log(get(testData, 'a.b.c'));
console.log(get(testData, 'd'));
console.log(get(testData, 'a.b.e'));

到目前为止最短的是:

(((( profile || {}) .content || {})[question.subject] || {}).saved || {}).includes(question._id) || false

在未来版本的JavaScript中,可以做:

 profile?.content?[question.subject]?.saved.includes(question._id)  || false

最新更新