使用 Lodash 的 get() 函数获取深度嵌套的属性
这 _.get()
Lodash 中的函数 让您可以在对象中获得深度嵌套的属性,而无需担心中间属性是否是 null
或者 undefined
, 例如,假设您有以下对象:
const landmark = {
name: 'Golden Gate Bridge',
// GeoJSON feature: https://geojson.org/
location: {
type: 'Feature',
properties: {
city: 'San Francisco',
state: 'California'
},
geometry: {
type: 'Point',
coordinates: [-122.4804438, 37.8199328]
}
}
};
要获得 location.geometry.type
的值,你可以使用 landmark.location.geometry.type
,但是如果 landmark.location
未定义,您将收到以下错误。
TypeError: Cannot read property 'geometry' of undefined
这 _.get()
功能使您可以安全地访问嵌套 location.geometry.type
属性,而不必明确检查是否 landmark
, landmark.location
,或者 landmark.location.geometry
未定义。
let type = _.get(landmark, 'location.geometry.type'); // 'Point'
delete landmark.location;
// `_.get()` doesn't error out, even though `landmark.location` is
// undefined.
type = _.get(landmark, 'location.geometry.type'); // undefined
// Even if `landmark` is `null`, `_.get()` does not error out.
type = _.get(null, 'location.geometry.type'); // undefined
默认值
第三个论据 _.get()
是默认值。 如果你传递一个默认值, _.get()
将返回通常返回的默认值 undefined
。
landmark.location.geometry.type = undefined;
// If the value of the property is `undefined`, `_.get()` will return
// the default value.
let type = _.get(landmark, 'location.geometry.type', 'default'); // 'default'
delete landmark.location;
// If the property doesn't exist, `_.get()` will also return the default
// value.
type = _.get(landmark, 'location.geometry.type', 'default'); // 'default'
null
对比 undefined
小心, _.get()
函数可以返回 null
,即使您指定了默认值。
landmark.location.geometry.type = null;
// If the value of the property is `null`, `_.get()` will **not** use
// the default value
let type = _.get(landmark, 'location.geometry.type', 'default'); // null
如果你想确定 _.get()
永远不会解析为空值,您需要使用 条件运算符 ?
。
landmark.location.geometry.type = null;
const checkDefault = (v, def) => v == null ? def : v;
// 'default'
let type = checkDefault(_.get(landmark, 'location.geometry.type'), 'default');
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论