使用 Lodash 的 get() 函数获取深度嵌套的属性

发布于 2022-08-13 13:09:35 字数 2764 浏览 141 评论 0

_.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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

顾忌

暂无简介

文章
评论
272 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文