![](/img/trans.png)
[英]Elegantly detecting the presence (and type) or absence of an Event Object inside a callback function
[英]How to check successive object presence elegantly
有没有办法更优雅地写这个?
if ("a" in obj && "b" in obj.a && "c" in obj.a.b)
而不是检查对象的每个阶段是否存在?
如果我这样做if ("c" in obj.ab)
如果a
或b
不存在,这将给出错误。
我一直发现 lodash _.has和_.get函数非常强大,您可以访问对象中深层嵌套的值,而无需大量代码来检查路径是否存在。
例如:
const obj = { a: { b: { c: 42 }}}; if (_.has(obj, "abc")) { console.log("Path exists"); } // Safe to access, will return undefined if path does not exist... console.log("Path value:", _.get(obj, "abc"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
function pluckDeep(key) {
return function(obj) {
return key.split('.').reduce((accum, key) => {
return accum[key]
}, obj);
}
}
const obj = { a: { b: { c: 42 }}};
if (pluckDeep('a.b.c')(obj)) {
// do something
}
这个柯里化函数可以通过使用 pluckDeep 函数的第一个参数来确定属性是否存在。
if (obj.a && obj.a.b && obj.a.b.c) {
// do something
}
if (obj.a?.b?.c) {
// do something
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.