假设我想做这样的事情:
const result = 'someKey' in myVar
? myVar.someKey
: myVar.anotherKey
我可以使用 get(myVar, 'someKey', get(myVar, 'anotherKey'))
实现同样的效果。我想知道是否还有另一种看起来比这更干净的 lodash 方法?
最佳答案
Lodash 中没有内置函数允许这样做(很遗憾)。然而,作为 Alexander Nied在他的回答中说,你可以很容易地为此创建一个自定义函数。我将使用 Lodash 功能而不是 vanilla JavaScript 来演示它是如何工作的:
function getFirst(item, paths) {
const notFound = Symbol("not found");
return _(paths)
.map(path => _.get(item, path, notFound))
.filter(result => result !== notFound)
.first();
}
const obj = {
a: {
b: {
c: 42
}
},
x: {
y: 1
},
z: 2
};
console.log(getFirst(obj, ['g']));
console.log(getFirst(obj, ['g', 'h', 'z']));
console.log(getFirst(obj, ['g', 'h', 'a.b.c', 'z']));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.15/lodash.min.js"></script>
Chaining using Lodash 是惰性求值的,所以序列是将第一个路径映射到 _.get(item, path)
,如果失败则返回一个唯一的 notFound
值。然后,如果 notFound
被丢弃,则将映射下一个值。这一直持续到有匹配项或 paths
的所有成员都用完并且值为 undefined
。
关于javascript - Lodash 返回键如果存在,否则返回另一个键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58493122/