javascript - Lodash return key if exists, otherwise return the other key
问题描述
Let's say I want to do something like:
const result = 'someKey' in myVar
? myVar.someKey
: myVar.anotherKey
I can achieve the same using get(myVar, 'someKey', get(myVar, 'anotherKey'))
. I was wondering if there is another lodash method that looks cleaner than that?
解决方案
No built in function in Lodash allows this (sadly). However, as Alexander Nied said in his answer, you can easily create a custom function for this. I will use Lodash functionality instead of vanilla JavaScript just to demonstrate how it can work:
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 is lazily evaluated, so the sequence is map first path to _.get(item, path)
and if it fails returns a unique notFound
value. Then if the notFound
is discarded the next value would be mapped. This continues until either there is a match or all the members of paths
are exhausted and the value is undefined
.
推荐阅读
- c# - .Net HttpResponseMessage.Content.ReadAsAsync
> 在 TResponse 值中始终为 null - angular - 使用 Git 如何在提交时忽略 node_modules
- ff - dsp.fft 和 fft 的区别
- python - 筛选比较,计算相似度分数,python
- python - 无法训练简单的 Char RNN
- python - 从列表中删除重复的列表元组
- javascript - 隐藏表单并显示 div
- webpack - Babel 7 这变成 _this angularjs
- java - 带有 SOAP Web 服务的消费者驱动契约
- ios - RxSwift,使用 RxBlocking 的测试不会结束