获取 lodash.get 路径中最后定义的元素(对象,路径)



给定一个对象:

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

我想要一个类似于lodash.get(obj, path)的函数,它返回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 only defined up to a.b

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

这是我想要的粗略实现:

const safeGet = (object, path) => {
const keys = path.split('.');
let current = object;
for (var i = 0; i < keys.length; i++){
const val = current[keys[i]]
if (val === undefined){
return current;
}
current = val;
}
}

默认情况下,在Lodash 中没有办法做到这一点,但这是我编写的一个比您当前显示的更简单的函数。希望这有帮助!

const obj1 = {
a: {
b: {
c: {
d: 5
}
}
}
};
const obj2 = {
a: {
b: {
c: {}
}
}
};
function getLastDefined(obj, searchPath) {
return _.get(obj, searchPath) || getLastDefined(obj, _.chain(searchPath).split('.').reverse().tail().reverse().join('.').value());
}
console.log(getLastDefined(obj1, 'a.b.c.d'));
console.log(getLastDefined(obj2, 'a.b.c.d'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>

最新更新