获取lodash.get(...)路径中的最后一个定义的元素

给定一个对象:

const obj = {
  a: {
    b: {
      c: {
        d: 5
      }
    }
  }
};

I want a function similar to lodash.get(obj, path), which returns the last defined variable in the path:

console.log(_.something(obj, 'a.b.c.d')) // 5, which is obj.a.b.c.d
// because obj.a.b.c.d is defined

console.log(_.something(obj, 'a.b.c.e')) // { d: 5 }, which is obj.a.b.c
// because the path is only defined up to obj.a.b.c

console.log(_.something(obj, 'a.b.f')) // { c: { d: 5 } }, which is a.b
// because the path is nonly defined up to a.b

我可以自己编写它,但是我想知道是否可以使用现有的lodash函数来完成它。我浏览了文档,但没有任何内容引起我的注意。

评论