我的问题
考虑对对象的嵌套属性进行比较:
display.entities.listAfter.text === 'blah';
如果嵌套查找中的某个属性不存在,我们将得到一个类型错误,例如:
TypeError: Cannot read property 'listAfter' of undefined
我试过什么
试着接住。工作,但不太优雅,我想知道是否有更好的方法。
我的私服
除了尝试和捕捉之外,是否有一种规范的方法在进行比较之前检查嵌套属性是否存在?
发布于 2018-09-13 19:20:40
我不知道规范,但我有时会这样做:
display.entities &&
display.entities.listAfter &&
display.entities.listAfter.text === 'blah'
当然,这很快就会变得笨重起来。如果你真的想让它看起来好看,那就去找房客吧!
https://lodash.com/docs/4.17.10#get
您可以提供.get函数的路径,如果找不到它,甚至可以指定默认路径。
_.get(display, 'entities.listAfter.text') === 'blah'
发布于 2018-09-13 21:30:01
对于具有智能默认值的嵌套属性,我喜欢使用简单的函数getter,如下所示:
const getValue = (obj = {}, path = []) => {
return path.reduce((xs, x) => (xs && xs[x]) ? xs[x] : undefined, obj);
};
const display = {
"entities": {
"listAfter": {
"text": 1
}
}
};
console.log(getValue(display, ['entities', 'listAfter', 'text']));
console.log(getValue(display, ['entities', 'listAfter', 'foo']));
console.log(getValue(display, ['entities', 'listAfter']));
https://stackoverflow.com/questions/52320363
复制相似问题